日期:2014-05-16 浏览次数:20813 次
//互斥锁
#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 对象, 虽然在&nb