使用mutex synchronization
的示例代码:
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
pthread_mutex_t mutex;
int sharedData=100;
void* criticalSection(void* arg)
{
pthread_mutex_lock(&mutex);
sharedData+=100;
printf("Shared Data has been modified to %d by thread %d\n",sharedData,pthread_self());
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main()
{
int rc;
pthread_t p1,p2;
rc = pthread_mutex_init(&mutex,NULL);
if (rc!=0)printf("Mutex init failed at %d %s ",__LINE__,__func__ );
pthread_create(&p1,NULL,criticalSection,NULL);
pthread_create(&p2,NULL,criticalSection,NULL);
pthread_join(p1,NULL);
pthread_join(p2,NULL);
rc = pthread_mutex_destroy(&mutex);
if (rc!=0)printf("Mutex destroy failed at %d %s ",__LINE__,__func__ );
return 0;
}
文件上说:
http://docs.oracle.com/cd/E19455-01/806-0630/6j9vkb8e0/index.html
Destroy
mutex_destroy() destroys the mutex object referenced by mp ; the mutex object
becomes uninitialized.
The space used by the destroyed mutex variable is not freed.
It needs to be explicitly reclaimed.
那么我们该如何回收空间呢?在上面的例子中,是否需要回收空间?如果是怎么做的?
我想如果
mutex_t
是在堆上创建的,我们应该使用类似delete
的东西来回收空间,在这种情况下,如果我没有错的话,就不需要了。有人能举一个需要回收空间的例子吗?或者说如何在
mutex_t
上初始化heap
对象? 最佳答案
它在动态分配的互斥体下提供的手册页中这样写道:
struct record {
int field1;
int field2;
mutex_t m;
} *r;
r = malloc(sizeof(struct record));
mutex_init(&r->m, USYNC_THREAD, NULL);
/*
* The fields in this record are accessed concurrently
* by acquiring the embedded lock.
*/
最后:
for (i = 0; i < 2; i++)
thr_join(0, 0, 0);
mutex_destroy(&r->m); /* first destroy mutex */
free(r); /* Then free memory */
这就是你要找的吗?
您引用的这句话仅仅意味着调用
mutex_destroy
并不免除您对动态分配的free
结构调用mutex_t
。编辑并确认,如果您使用的是pthread库,您可能应该查看以下内容:
http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_destroy.html
关于c - 使用Mutex_destroy()时如何释放内存:Posix多线程,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23863800/