当前位置: 技术问答>linux和unix
菜鸟一枚,互斥锁问题
来源: 互联网 发布时间:2017-05-01
本文导语: //互斥锁 #include #include #include #include void *fun(void *p); int main() { pthread_t pth = 0; pthread_mutex_t mutex; int ret = 0; char buf[50] = {0}; ret = pthread_mutex_init(&mutex,NULL); if(0 > ret) { perror("pthread_mutex_init error"); return 1; }...
//互斥锁
#include
#include
#include
#include
void *fun(void *p);
int main()
{
pthread_t pth = 0;
pthread_mutex_t mutex;
int ret = 0;
char buf[50] = {0};
ret = pthread_mutex_init(&mutex,NULL);
if(0 > ret)
{
perror("pthread_mutex_init error");
return 1;
}
ret = pthread_create(&pth,NULL,fun,&mutex);
if(0 > ret)
{
perror("pthread_create error");
return 1;
}
pthread_mutex_lock(&mutex);
printf("this parent after 10s childn");
sleep(10);
pthread_mutex_unlock(&mutex);
pthread_join(pth,NULL);
exit;
}
void *fun(void *p)
{
pthread_mutex_t mutex = *((pthread_mutex_t *)p);
pthread_mutex_lock(&mutex);
printf("this is child after 5s parentn");
sleep(5);
pthread_mutex_unlock(&mutex);
pthread_exit;
}
变量mutex定义为全局变量没问题,向子线程传参就不行了,会一直等待,求解?
|
不要拷贝MUTEX对象
#include
#include
#include
#include
void *fun(void *p);
int main()
{
pthread_t pth = 0;
pthread_mutex_t mutex;
int ret = 0;
char buf[50] = {0};
ret = pthread_mutex_init(&mutex,NULL);
if(0 > ret)
{
perror("pthread_mutex_init error");
return 1;
}
ret = pthread_create(&pth,NULL,fun,&mutex);
if(0 > ret)
{
perror("pthread_create error");
return 1;
}
pthread_mutex_lock(&mutex);
printf("this parent after 10s childn");
sleep(10);
pthread_mutex_unlock(&mutex);
pthread_join(pth,NULL);
exit;
}
void *fun_bad(void *p)
{
pthread_mutex_t mutex = *((pthread_mutex_t *)p);
/*
* 不要拷贝 mutex 对象, 虽然在 FreeBSD 是可以这么做的。
*/
pthread_mutex_lock(&mutex);
printf("this is child after 5s parentn");
sleep(5);
pthread_mutex_unlock(&mutex);
pthread_exit; /* 函数调用不带这么写的!!! */
}
/*
* IEEE Std 1003.1-2008
*
* pthread_mutex_destroy, pthread_mutex_init - destroy and initialize a mutex
*
* DESCRIPTION:
*
* ...
*
* Only mutex itself may be used for performing synchronization.
* The result of referring to copies of mutex in calls to
* pthread_mutex_lock(), pthread_mutex_trylock(), pthread_mutex_unlock(),
* and pthread_mutex_destroy() is undefined.
*
* ...
*/
void *fun(void *p)
{
pthread_mutex_t *mutex = (pthread_mutex_t *)p;
pthread_mutex_lock(mutex);
printf("this is child after 5s parentn");
sleep(5);
pthread_mutex_unlock(mutex);
pthread_exit(NULL);
}
本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。