菜鸟一枚,互斥锁问题
//互斥锁
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
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 child\n");
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 parent\n");
sleep(5);
pthread_mutex_unlock(&mutex);
pthread_exit;
}
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
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 child\n");
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 parent\n");
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 parent\n");
sleep(5);
pthread_mutex_unlock(mutex);
pthread_exit(NULL);
}