您的位置:首页 > 编程语言 > C语言/C++

用C++11 thread 类编写多线程程序

2013-12-22 20:19 274 查看
用thread类写多线程程序比用posix 线程库方便很多,而且增强了可移植性.

thread类简介:

构造函数:

默认构造函数构造一个不代表任何执行线程的thread对象,可以在需要时使用operator=把一个新构造thread转移给它(如示例所示)。

thread类不提供拷贝构造函数。

初始化构造函数第一个参数为函数的入口地址(即函数名),后面依次是此函数的参数。相当于posix的  pthread_creat();不过用起来要方便的多。

get_id():返回线程id;

join():相当于posix的pthread_join(),用来等待子线程结束。

示例代码:

//test.cpp

#include<iostream>
#include<thread>
using namespace std;
void fun1()
{
cout<<"A function for test"<<endl;
}
void fun2(int x)
{
cout<<"Receive number "<<x<<endl;
}
int main()
{
thread a(fun1);
thread b;
b=thread(fun2,1);
a.join();
b.join();
return 0;
}

用linux g++编译器,输入以下命令:g++ -std=c++0x -o test test.cpp -pthread
-std=c++0x 指定使用c++11,因为默认使用老版本,仍然要使用-pthread 链接线程库,应该是因为linux下的pthread类是用posix线程库实现的。

下面看一个好像是今年某个公司的一个笔试题。

问题是利用线程调度的随机性产生字符串S=“abcdefg”的随机序列。

利用thread类的代码如下:

#include<iostream>
#include<thread>
using namespace std;
void fun(char c)
{
sleep(1);
cout<<c;
}
int main()
{
thread t[7];
int i;
for(i=0;i<7;i++)
t[i]=thread(fun,i+'a');
for(i=0;i<7;i++)
t[i].join();
cout<<endl;
}
运行结果随机性不是太好,感觉应该是线程调度本身不是完全随机,不知道是否有更好的方法。
用mutex类保护临界区。

mutex类有着和thread类同样的好长,代码简单,可移植。

mutex:

mutex()  //构造函数,无参数,产生unlock状态mutex对象。

lock()   //如果当前是unlock状态则lock,否则阻塞。

try_lock()  //如果当前是unlock状态则lock,否则继续执行。

unlock()    //解锁,如果当前是unlock状态,则产生未定义行为。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++11 多线程 thread