c++多线程编程

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
转载链接: https://blog.csdn.net/hitwengqi/article/details/8015646

一直对多线程编程这一块很陌生,决定花一点时间整理一下。

os:ubuntu 10.04  c++

1.最基础,进程同时创建5个线程,各自调用同一个函数


 
 
  1. #include <iostream>
  2. #include <pthread.h> //多线程相关操作头文件,可移植众多平台
  3. using namespace std;
  4. #define NUM_THREADS 5 //线程数
  5. void* say_hello( void* args )
  6. {
  7. cout << "hello..." << endl;
  8. } //函数返回的是函数指针,便于后面作为参数
  9. int main()
  10. {
  11. pthread_t tids[NUM_THREADS]; //线程id
  12. for( int i = 0; i < NUM_THREADS; ++i )
  13. {
  14. int ret = pthread_create( &tids[i], NULL, say_hello, NULL ); //参数:创建的线程id,线程参数,线程运行函数的起始地址,运行函数的参数
  15. if( ret != 0 ) //创建线程成功返回0
  16. {
  17. cout << "pthread_create error:error_code=" << ret << endl;
  18. }
  19. }
  20. pthread_exit( NULL ); //等待各个线程退出后,进程才结束,否则进程强制结束,线程处于未终止的状态
  21. }
输入命令:g++ -o muti_thread_test_1 muti_thread_test_1.cpp -lpthread

注意:

1)此为c++程序,故用g++来编译生成可执行文件,并且要调用处理多线程操作相关的静态链接库文件pthread。

2)-lpthread 编译选项到位置可任意,如g++ -lpthread -o muti_thread_test_1 muti_thread_test_1.cpp

3)注意gcc和g++的区别,转到此文:点击打开链接

测试结果:


 
 
  1. wq@wq- desktop:~ /coding/muti_thread$ ./muti_thread_test_1
  2. hello...hello...
  3. hello...
  4. hello...
  5. hello...

 
 
  1. wq@wq- desktop:~ /coding/muti_thread$ ./muti_thread_test_1
  2. hello...hello...hello...
  3. hello...
  4. hello...

可知,两次运行的结果会有差别,这不是多线程的特点吧?这显然没有同步?还有待进一步探索...

多线程的运行是混乱的,混乱就是正常?


2.线程调用到函数在一个类中,那必须将该函数声明为静态函数函数

因为静态成员函数属于静态全局区,线程可以共享这个区域,故可以各自调用。


 
 
  1. #include <iostream>
  2. #include <pthread.h>
  3. using namespace std;
  4. #define NUM_THREADS 5
  5. class Hello
  6. {
  7. public:
  8. static void* say_hello( void* args )
  9. {
  10. cout << "hello..." << endl;
  11. }
  12. };
  13. int main()
  14. {
  15. pthread_t tids[NUM_THREADS];
  16. for( int i = 0; i < NUM_THREADS; ++i )
  17. {
  18. int ret = pthread_create( &tids[i], NULL, Hello::say_hello, NULL );
  19. if( ret != 0 )
  20. {
  21. cout << "pthread_create error:error_code" << ret << endl;
  22. }
  23. }
  24. pthread_exit( NULL );
  25. }

测试结果:


 
 
  1. wq@wq- desktop:~ /coding/muti_thread$ ./muti_thread_test_2
  2. hello...
  3. hello...
  4. hello...
  5. hello...
  6. hello...

 
 
  1. wq@wq- desktop:~ /coding/muti_thread$ ./muti_thread_test_2
  2. hello...hello...hello...
  3. hello...
  4. hello...

3.如何在线程调用函数时传入参数呢?

先看下面修改的代码,传入线程编号作为参数:


 
 
  1. #include <iostream>
  2. #include <pthread.h> //多线程相关操作头文件,可移植众多平台
  3. using namespace std;
  4. #define NUM_THREADS 5 //线程数
  5. void* say_hello( void* args )
  6. {
  7. int i = *( ( int*)args ); //对传入的参数进行强制类型转换,由无类型指针转变为整形指针,再用*读取其指向到内容
  8. cout << "hello in " << i << endl;
  9. } //函数返回的是函数指针,便于后面作为参数
  10. int main()
  11. {
  12. pthread_t tids[NUM_THREADS]; //线程id
  13. cout << "hello in main.." << endl;
  14. for( int i = 0; i < NUM_THREADS; ++i )
  15. {
  16. int ret = pthread_create( &tids[i], NULL, say_hello, ( void*)&i ); //传入到参数必须强转为void*类型,即无类型指针,&i表示取i的地址,即指向i的指针
  17. cout << "Current pthread id = " << tids[i] << endl; //用tids数组打印创建的进程id信息
  18. if( ret != 0 ) //创建线程成功返回0
  19. {
  20. cout << "pthread_create error:error_code=" << ret << endl;
  21. }
  22. }
  23. pthread_exit( NULL ); //等待各个线程退出后,进程才结束,否则进程强制结束,线程处于未终止的状态
  24. }
测试结果:

 
 
  1. wq@wq-desktop:~/coding/muti_thread$ ./muti_thread_test_3
  2. hello in main..
  3. Current pthread id = 3078458224
  4. Current pthread id = 3070065520
  5. hello in hello in 2
  6. 1
  7. Current pthread id = hello in 2
  8. 3061672816
  9. Current pthread id = 3053280112
  10. hello in 4
  11. Current pthread id = hello in 4
  12. 3044887408
显然不是想要的结果,调用顺序很乱,这是为什么呢?

这是因为多线程到缘故,主进程还没开始对i赋值,线程已经开始跑了...?

修改代码如下:


 
 
  1. #include <iostream>
  2. #include <pthread.h> //多线程相关操作头文件,可移植众多平台
  3. using namespace std;
  4. #define NUM_THREADS 5 //线程数
  5. void* say_hello( void* args )
  6. {
  7. cout << "hello in thread " << *( ( int *)args ) << endl;
  8. } //函数返回的是函数指针,便于后面作为参数
  9. int main()
  10. {
  11. pthread_t tids[NUM_THREADS]; //线程id
  12. int indexes[NUM_THREADS]; //用来保存i的值避免被修改
  13. for( int i = 0; i < NUM_THREADS; ++i )
  14. {
  15. indexes[i] = i;
  16. int ret = pthread_create( &tids[i], NULL, say_hello, ( void*)&(indexes[i]) );
  17. if( ret != 0 ) //创建线程成功返回0
  18. {
  19. cout << "pthread_create error:error_code=" << ret << endl;
  20. }
  21. }
  22. for( int i = 0; i < NUM_THREADS; ++i )
  23. pthread_join( tids[i], NULL ); //pthread_join用来等待一个线程的结束,是一个线程阻塞的函数
  24. }
测试结果:


 
 
  1. wq@wq- desktop:~ /coding/muti_thread$ ./muti_thread_test_3
  2. hello in thread hello in thread hello in thread hello in thread hello in thread 30124

这是正常的吗?感觉还是有问题...待续

代码中如果没有pthread_join主线程会很快结束从而使整个进程结束,从而使创建的线程没有机会开始执行就结束了。加入pthread_join后,主线程会一直等待直到等待的线程结束自己才结束,使创建的线程有机会执行。


4.线程创建时属性参数的设置pthread_attr_t及join功能的使用

线程的属性由结构体pthread_attr_t进行管理。

typedef struct
{
    int                           detachstate;     线程的分离状态
    int                          schedpolicy;   线程调度策略
    struct sched_param      schedparam;   线程的调度参数
    int inheritsched; 线程的继承性 
    int scope; 线程的作用域 
    size_t guardsize; 线程栈末尾的警戒缓冲区大小 
    int stackaddr_set; void * stackaddr; 线程栈的位置 
    size_t stacksize; 线程栈的大小
}pthread_attr_t;


 
 
  1. #include <iostream>
  2. #include <pthread.h>
  3. using namespace std;
  4. #define NUM_THREADS 5
  5. void* say_hello( void* args )
  6. {
  7. cout << "hello in thread " << *(( int * )args) << endl;
  8. int status = 10 + *(( int * )args); //线程退出时添加退出的信息,status供主程序提取该线程的结束信息
  9. pthread_exit( ( void* )status );
  10. }
  11. int main()
  12. {
  13. pthread_t tids[NUM_THREADS];
  14. int indexes[NUM_THREADS];
  15. pthread_attr_t attr; //线程属性结构体,创建线程时加入的参数
  16. pthread_attr_init( &attr ); //初始化
  17. pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ); //是设置你想要指定线程属性参数,这个参数表明这个线程是可以join连接的,join功能表示主程序可以等线程结束后再去做某事,实现了主程序和线程同步功能
  18. for( int i = 0; i < NUM_THREADS; ++i )
  19. {
  20. indexes[i] = i;
  21. int ret = pthread_create( &tids[i], &attr, say_hello, ( void* )&( indexes[i] ) );
  22. if( ret != 0 )
  23. {
  24. cout << "pthread_create error:error_code=" << ret << endl;
  25. }
  26. }
  27. pthread_attr_destroy( &attr ); //释放内存
  28. void *status;
  29. for( int i = 0; i < NUM_THREADS; ++i )
  30. {
  31. int ret = pthread_join( tids[i], &status ); //主程序join每个线程后取得每个线程的退出信息status
  32. if( ret != 0 )
  33. {
  34. cout << "pthread_join error:error_code=" << ret << endl;
  35. }
  36. else
  37. {
  38. cout << "pthread_join get status:" << ( long)status << endl;
  39. }
  40. }
  41. }
测试结果:


 
 
  1. wq@wq-desktop:~/coding/muti_thread$ ./muti_thread_test_4
  2. hello in thread hello in thread hello in thread hello in thread 0hello in thread 321
  3. 4
  4. pthread_join get status: 10
  5. pthread_join get status: 11
  6. pthread_join get status: 12
  7. pthread_join get status: 13
  8. pthread_join get status: 14

5.互斥锁的实现
互斥锁是实现线程同步的一种机制,只要在临界区前后对资源加锁就能阻塞其他进程的访问。


 
 
  1. #include <iostream>
  2. #include <pthread.h>
  3. using namespace std;
  4. #define NUM_THREADS 5
  5. int sum = 0; //定义全局变量,让所有线程同时写,这样就需要锁机制
  6. pthread_mutex_t sum_mutex; //互斥锁
  7. void* say_hello( void* args )
  8. {
  9. cout << "hello in thread " << *(( int * )args) << endl;
  10. pthread_mutex_lock( &sum_mutex ); //先加锁,再修改sum的值,锁被占用就阻塞,直到拿到锁再修改sum;
  11. cout << "before sum is " << sum << " in thread " << *( ( int* )args ) << endl;
  12. sum += *( ( int* )args );
  13. cout << "after sum is " << sum << " in thread " << *( ( int* )args ) << endl;
  14. pthread_mutex_unlock( &sum_mutex ); //释放锁,供其他线程使用
  15. pthread_exit( 0 );
  16. }
  17. int main()
  18. {
  19. pthread_t tids[NUM_THREADS];
  20. int indexes[NUM_THREADS];
  21. pthread_attr_t attr; //线程属性结构体,创建线程时加入的参数
  22. pthread_attr_init( &attr ); //初始化
  23. pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ); //是设置你想要指定线程属性参数,这个参数表明这个线程是可以join连接的,join功能表示主程序可以等线程结束后再去做某事,实现了主程序和线程同步功能
  24. pthread_mutex_init( &sum_mutex, NULL ); //对锁进行初始化
  25. for( int i = 0; i < NUM_THREADS; ++i )
  26. {
  27. indexes[i] = i;
  28. int ret = pthread_create( &tids[i], &attr, say_hello, ( void* )&( indexes[i] ) ); //5个进程同时去修改sum
  29. if( ret != 0 )
  30. {
  31. cout << "pthread_create error:error_code=" << ret << endl;
  32. }
  33. }
  34. pthread_attr_destroy( &attr ); //释放内存
  35. void *status;
  36. for( int i = 0; i < NUM_THREADS; ++i )
  37. {
  38. int ret = pthread_join( tids[i], &status ); //主程序join每个线程后取得每个线程的退出信息status
  39. if( ret != 0 )
  40. {
  41. cout << "pthread_join error:error_code=" << ret << endl;
  42. }
  43. }
  44. cout << "finally sum is " << sum << endl;
  45. pthread_mutex_destroy( &sum_mutex ); //注销锁
  46. }
测试结果:

 
 
  1. wq@wq-desktop:~/coding/muti_thread$ ./muti_thread_test_5
  2. hello in thread hello in thread hello in thread 410
  3. before sum is hello in thread 0 in thread 4
  4. after sum is 4 in thread 4hello in thread
  5. 2
  6. 3
  7. before sum is 4 in thread 1
  8. after sum is 5 in thread 1
  9. before sum is 5 in thread 0
  10. after sum is 5 in thread 0
  11. before sum is 5 in thread 2
  12. after sum is 7 in thread 2
  13. before sum is 7 in thread 3
  14. after sum is 10 in thread 3
  15. finally sum is 10
可知,sum的访问和修改顺序是正常的,这就达到了多线程的目的了,但是线程的运行顺序是混乱的,混乱就是正常?

6.信号量的实现
信号量是线程同步的另一种实现机制,信号量的操作有signal和wait,本例子采用条件信号变量pthread_cond_t tasks_cond;
信号量的实现也要给予锁机制。


 
 
  1. #include <iostream>
  2. #include <pthread.h>
  3. #include <stdio.h>
  4. using namespace std;
  5. #define BOUNDARY 5
  6. int tasks = 10;
  7. pthread_mutex_t tasks_mutex; //互斥锁
  8. pthread_cond_t tasks_cond; //条件信号变量,处理两个线程间的条件关系,当task>5,hello2处理,反之hello1处理,直到task减为0
  9. void* say_hello2( void* args )
  10. {
  11. pthread_t pid = pthread_self(); //获取当前线程id
  12. cout << "[" << pid << "] hello in thread " << *( ( int* )args ) << endl;
  13. bool is_signaled = false; //sign
  14. while( 1)
  15. {
  16. pthread_mutex_lock( &tasks_mutex ); //加锁
  17. if( tasks > BOUNDARY )
  18. {
  19. cout << "[" << pid << "] take task: " << tasks << " in thread " << *( ( int*)args ) << endl;
  20. --tasks; //modify
  21. }
  22. else if( !is_signaled )
  23. {
  24. cout << "[" << pid << "] pthread_cond_signal in thread " << *( ( int* )args ) << endl;
  25. pthread_cond_signal( &tasks_cond ); //signal:向hello1发送信号,表明已经>5
  26. is_signaled = true; //表明信号已发送,退出此线程
  27. }
  28. pthread_mutex_unlock( &tasks_mutex ); //解锁
  29. if( tasks == 0 )
  30. break;
  31. }
  32. }
  33. void* say_hello1( void* args )
  34. {
  35. pthread_t pid = pthread_self(); //获取当前线程id
  36. cout << "[" << pid << "] hello in thread " << *( ( int* )args ) << endl;
  37. while( 1)
  38. {
  39. pthread_mutex_lock( &tasks_mutex ); //加锁
  40. if( tasks > BOUNDARY )
  41. {
  42. cout << "[" << pid << "] pthread_cond_signal in thread " << *( ( int* )args ) << endl;
  43. pthread_cond_wait( &tasks_cond, &tasks_mutex ); //wait:等待信号量生效,接收到信号,向hello2发出信号,跳出wait,执行后续
  44. }
  45. else
  46. {
  47. cout << "[" << pid << "] take task: " << tasks << " in thread " << *( ( int*)args ) << endl;
  48. --tasks;
  49. }
  50. pthread_mutex_unlock( &tasks_mutex ); //解锁
  51. if( tasks == 0 )
  52. break;
  53. }
  54. }
  55. int main()
  56. {
  57. pthread_attr_t attr; //线程属性结构体,创建线程时加入的参数
  58. pthread_attr_init( &attr ); //初始化
  59. pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ); //是设置你想要指定线程属性参数,这个参数表明这个线程是可以join连接的,join功能表示主程序可以等线程结束后再去做某事,实现了主程序和线程同步功能
  60. pthread_cond_init( &tasks_cond, NULL ); //初始化条件信号量
  61. pthread_mutex_init( &tasks_mutex, NULL ); //初始化互斥量
  62. pthread_t tid1, tid2; //保存两个线程id
  63. int index1 = 1;
  64. int ret = pthread_create( &tid1, &attr, say_hello1, ( void* )&index1 );
  65. if( ret != 0 )
  66. {
  67. cout << "pthread_create error:error_code=" << ret << endl;
  68. }
  69. int index2 = 2;
  70. ret = pthread_create( &tid2, &attr, say_hello2, ( void* )&index2 );
  71. if( ret != 0 )
  72. {
  73. cout << "pthread_create error:error_code=" << ret << endl;
  74. }
  75. pthread_join( tid1, NULL ); //连接两个线程
  76. pthread_join( tid2, NULL );
  77. pthread_attr_destroy( &attr ); //释放内存
  78. pthread_mutex_destroy( &tasks_mutex ); //注销锁
  79. pthread_cond_destroy( &tasks_cond ); //正常退出
  80. }
测试结果:
先在线程2中执行say_hello2,再跳转到线程1中执行say_hello1,直到tasks减到0为止。


 
 
  1. wq@wq-desktop:~/coding/muti_thread$ ./muti_thread_test_6
  2. [ 3069823856] hello in thread 2
  3. [ 3078216560] hello in thread 1[ 3069823856] take task: 10 in thread 2
  4. [ 3069823856] take task: 9 in thread 2
  5. [ 3069823856] take task: 8 in thread 2
  6. [ 3069823856] take task: 7 in thread 2
  7. [ 3069823856] take task: 6 in thread 2
  8. [ 3069823856] pthread_cond_signal in thread 2
  9. [ 3078216560] take task: 5 in thread 1
  10. [ 3078216560] take task: 4 in thread 1
  11. [ 3078216560] take task: 3 in thread 1
  12. [ 3078216560] take task: 2 in thread 1
  13. [ 3078216560] take task: 1 in thread 1
到此,对多线程编程有了一个初步的了解,当然还有其他实现线程同步的机制,有待进一步探索。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值