码迷,mamicode.com
首页 > 编程语言 > 详细

c++多线程

时间:2015-02-07 14:22:16      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:

1、代码

//thread.cpp
#include <iostream> #include <pthread.h> //多线程相关操作头文件,可移植众多平台 using namespace std; #define NUM_THREADS 5 //线程数 void* say_hello( void* args ) { cout << "hello..." << endl; } //函数返回的是函数指针,便于后面作为参数 int main() { pthread_t tids[NUM_THREADS]; //线程id for( int i = 0; i < NUM_THREADS; ++i ) { int ret = pthread_create( &tids[i], NULL, say_hello, NULL ); //参数:创建的线程id,线程参数,线程运行函数的起始地址,运行函数的参数 if( ret != 0 ) //创建线程成功返回0 { cout << "pthread_create error:error_code=" << ret << endl; } } pthread_exit( NULL ); //等待各个线程退出后,进程才结束,否则进程强制结束,线程处于未终止的状态 }

2、Linux编译:g++ -o thread thread.cpp

技术分享

3.输出结果可以看出,运行两次,得到的结果是不一样的。

参考:http://blog.csdn.net/hitwengqi/article/details/8015646

 4.在vs2010中运行  缺少的thread预编译包(下载地址: http://pan.baidu.com/s/1EVKbO 密码: jm9d)

      多次运行结果总是有变化。

技术分享技术分享

c++多线程

标签:

原文地址:http://www.cnblogs.com/lwngreat/p/4278665.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!