源码如下
#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include "iostream"
#include <pthread.h>
using namespace std;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; //初始化 互斥锁
int tmp;
void* thread(void *arg)
{
cout << "thread id is " << pthread_self() << endl; //打印当前线程id
pthread_mutex_lock(&mutex); //加锁 place1
tmp = 12;
cout << "Now a is " << tmp << endl;
sleep(5);
cout << "Now after a is " << tmp << endl;
pthread_mutex_unlock(&mutex); //解锁 place1
return NULL;
}
void* thread2(void *arg)
{
cout << "thread id2 is " << pthread_self() << endl;
pthread_mutex_lock(&mutex); //加锁 place1
tmp = 22;
cout << "Now a is " << tmp << endl;
sleep(5);
cout << "Now after a is " << tmp << endl;
pthread_mutex_unlock(&mutex); //解锁 place1
return NULL;
}
int main()
{
//thread id
pthread_t id;
cout << "main thread id is " << pthread_self() << endl;
tmp = 3;
cout << "In main func tmp = " << tmp << endl;
if (!pthread_create(&id, NULL, thread, NULL))
{
cout << "Create thread success!" << endl;
}
else
{
cout << "Create thread failed!" << endl;
}
//thread id2
pthread_t id2;
cout << "main thread id is " << pthread_self() << endl;
tmp = 13;
cout << "In main func tmp = " << tmp << endl;
if (!pthread_create(&id2, NULL, thread2, NULL))
{
cout << "Create thread success!" << endl;
}
else
{
cout << "Create thread failed!" << endl;
}
pthread_join(id, NULL); //等待一个线程的结束。阻塞 place2
pthread_join(id2, NULL); //等待一个线程的结束。阻塞 place2
pthread_mutex_destroy(&mutex);
return 0;
}
主线程起了 id 和id2两个子线程。
按照上述源码:
执行结果是,
此时id和id2是同步的。
异步创建好两个线程,id 和id2,然后主程序阻塞在 pthread_join(id, NULL);
然后id 和id2 随即(貌似总是id2先) 执行各自的线程函数;
由于加锁了,所以若先执行了id2,则会在id2中一直运行,包括里面的sleep5s;
5s之后,id2释放锁,id拿到锁,才进入到id的线程函数中。
id线程函数执行完成后才执行pthread_join的阻塞函数。
一.若只将 4处place1注释掉。
则此时 id和id2两个线程是异步的
异步创建好两个线程,id 和id2,然后主程序阻塞在 pthread_join(id, NULL);
id和id2同时执行,同时sleep 5s,5s之后,同时离开各自的线程函数。
然后进入到thread的阻塞函数中去。
二.若只将 2出place2注释掉
main函数创建完两个线程后,也不管子线程的工作情况,main函数继续执行,知道return。
此时,两个子函数都还没有执行完。