【发布时间】:2014-05-26 06:14:47
【问题描述】:
使用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 之类的东西来回收空间。在这种情况下不需要,如果我没记错的话。
有人可以举一个需要空间回收的例子吗?或者说如何在heap上初始化mutex_t对象?
【问题讨论】:
-
这是posix的多线程而不是oracle的。
标签: c multithreading posix