linux下互斥锁的使用

来源:互联网 发布:u盘启动linux系统 编辑:程序博客网 时间:2024/05/07 01:29

源码如下


#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;  //打印当前线程idpthread_mutex_lock(&mutex);  //加锁  place1tmp = 12;  cout << "Now a is " << tmp << endl;  sleep(5);cout << "Now after a is " << tmp << endl;  pthread_mutex_unlock(&mutex);  //解锁place1return NULL;  }  void* thread2(void *arg)  {  cout << "thread id2 is " << pthread_self() << endl;  pthread_mutex_lock(&mutex);  //加锁place1tmp = 22;  cout << "Now a is " << tmp << endl;  sleep(5);cout << "Now after a is " << tmp << endl;  pthread_mutex_unlock(&mutex);  //解锁place1return NULL;  }  int main()  {  //thread idpthread_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 id2pthread_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);  //等待一个线程的结束。阻塞place2pthread_join(id2, NULL);  //等待一个线程的结束。阻塞place2pthread_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。

    此时,两个子函数都还没有执行完。


 

0 0
原创粉丝点击