使用互斥锁同步
的示例代码:
#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
的东西来回收空间。在这种情况下不需要,如果我没记错的话。
有人可以举例说明需要空间回收的地方吗?或者说如何初始化 heap
上的 mutex_t
对象?
好吧,在您在动态分配的互斥量 下提供的手册页中,它就说明了这一点:
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
并不能免除您在动态分配的 mutex_t
结构上调用 free
。
编辑 是的,如果您使用的是 pthread 库,您可能应该看这里:
http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_destroy.html
我是一名优秀的程序员,十分优秀!