本文主要是介绍线程C++,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#include <thread>
#include <chrono>
#include <cmath>
#include <mutex>
#include <iostream>
using namespace std;mutex mtx;
void threadCommunicat()
{int ans = 0;while (ans<=3){mtx.lock();//上锁cout << "ans=" << ans << endl;ans++;mtx.unlock();//解锁this_thread::sleep_for(chrono::microseconds(int(0.5 * pow(10, 6))));//0.5秒}}
int main()
{thread a(threadCommunicat);a.detach();//主线程执行完则直接结束 说明添加线程的方式 cout << "next" << endl;thread b(threadCommunicat);b.join();//子线程结束后才执行后续代码 说明添加线程的方式
}
运行效果:
这篇关于线程C++的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!