设为首页 加入收藏

TOP

C++多线程编程(二)
2016-08-19 16:03:48 】 浏览:663
Tags:线程 编程
space std; void* change_value(void* args) { cout << "This thread value is " << *((int *)args) << endl; int result = *((int *)args) + 10; pthread_exit((void*)result); } int main() { int value1 = 1,value2 = 3; void* result; pthread_t pt1,pt2; int ret = pthread_create(&pt1, NULL, change_value, (void*)&value1); if(ret != 0) { cout << "pthread_create error:error_code=" << ret << endl; } pthread_join(pt1,&result); cout << "The thread1's result is " << (int)result << endl; ret = pthread_create(&pt2, NULL, change_value, (void*)&value2); if(ret != 0) { cout << "pthread_create error:error_code=" << ret << endl; } pthread_join(pt2,&result); cout << "The thread2's result is " << (int)result << endl; return 0; }

互斥锁

互斥锁的作用是访问数据时可以保证是被一个线程所访问,并不能控制线程执行顺序的先后。

#include 
  
   
#include 
   
     using namespace std; // 定义第一个线程类 class MyThread { public: static int flag; // 定义线程启动的函数,必须是静态的 static void* fun1(void* args); static void* fun2(void* args); }; int MyThread::flag = 0; pthread_mutex_t sum_mutex; int temp; void* MyThread::fun1(void* args) { // 上锁 pthread_mutex_lock(&sum_mutex); cout << "This is " << ++flag << " Thread1!\n"; // 解锁 pthread_mutex_unlock(&sum_mutex); } void* MyThread::fun2(void* args) { pthread_mutex_lock(&sum_mutex); cout << "This is " << ++flag << " Thread2!\n"; pthread_mutex_unlock(&sum_mutex); } int main() { pthread_t pt; if(pthread_create(&pt,NULL,MyThread::fun1,NULL) != 0) { cout << "Error in create first Thread!\n"; } if(pthread_create(&pt,NULL,MyThread::fun2,NULL) != 0) { cout << "Error in create first Thread!\n"; } pthread_exit(NULL); cout << temp << endl; pthread_mutex_destroy(&sum_mutex); return 0; } 
   
  

基本到此为止,多线程的一些最基本的使用就到此结束了,在使用的过程中,发现自己的很多基础知识都有很多断层,大概这就是我用到哪里学到哪里的一个大BUG。这样也好,从最基本的开始一点一点来检查。

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C++泛型编程 下一篇STL算法(19)――for_each()和tr..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目