#include <stdio.h>
#include <time.h>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* doit(void* arg)
{
printf("pid = %d begin doit ...\n", static_cast<int>(getpid()));
pthread_mutex_lock(&mutex);
struct timespec ts = { 2, 0 };
nanosleep(&ts, NULL);
pthread_mutex_unlock(&mutex);
printf("pid = %d end doit ...\n", static_cast<int>(getpid()));
return NULL;
}
int main(void)
{
printf("pid = %d Entering main ...\n", static_cast<int>(getpid()));
pthread_t tid;
pthread_create(&tid, NULL, doit, NULL);
struct timespec ts = { 1, 0 };
nanosleep(&ts, NULL);
if (fork() == 0)//fork之后,子进程从下面开始执行
{
doit(NULL);//父进程执行到这一句的时候会暂停一会,等父进程中的线程对mutex解锁后执行这一句
//但是子进程执行到这一句的时候,就会一直等待,因为子进程中没有线程对mutex解锁
}
pthread_join(tid, NULL);
printf("pid = %d Exiting main ...\n", static_cast<int>(getpid()));
return 0;
}