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

C++多线程与临界资源实例

2015-06-14 10:26 183 查看
在C++中引入thread头文件可以很容易地实现多线程。

#include <thread>


引入头文件后,我们需要将每一个线程写成函数的形式。如示例中的inc()与dec()函数。

void inc()
{
int time = TIME;
while(time--)
{
num++;
}
}
void dec()
{
int time = TIME;
while(time--)
{
num--;
}
}


之后我们通过线程类的初始化就可以很容易地创建并运行线程。

std::thread t1(inc);
std::thread t2(dec);


注意:在主线程中,我们需要用thread.join() 来阻塞等待结束每一个线程。否则主线程提前结束程序会出错。



下面是这个示例中完整的代码,代码中模拟了线程对临界资源的操作。不同的运行,num的值可能会不一样。这在我们的实际的编程中要注意。

#include <thread>
#include <iostream>
#define TIME 1000000
int num = 0;
void inc() { int time = TIME; while(time--) { num++; } } void dec() { int time = TIME; while(time--) { num--; } }
int main()
{
std::thread t1(inc);
std::thread t2(dec);

std::cout << "thread begin" << std::endl;

t1.join();
t2.join();

std::cout << "The num is : " << num << std::endl;
return 0;
}


如有遗漏,欢迎留言补充。转载请注明出处
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: