一个初级的线程函数
2022-08-29 23:58:48

一个初级的线程函数

创建10个线程,每个线程内进行计数操作,有锁. 

对认识线程,有一定的帮助作用。

#include <iostream>  // std::cout
#include <thread>    // std::thread
#include <mutex>     // std::mutex
using namespace std;
volatile int counter(0);  //定义一个全局变量,当作计数器,用于累加
std::mutex mtx; //用于包含 counter 的互斥锁
void thrfunc()
{
    for(int i=0;i<50;++i)
    {
        // 互斥锁上锁
        if(mtx.try_lock())
        {
            ++counter;  // 计数器累加
            cout<<counter<<endl;
            mtx.unlock(); // 互斥锁解锁 
        }
        else
        {
            cout <<"try_lock false"<<endl;
        }
    }
}

int main(int argc, const char* argv[])
{
    std::thread threads[10];
    for(int i=0;i<10;++i)
    {
        threads[i] = std::thread(thrfunc); // 启动10个线程
    }
    for(auto & th:threads)
    {
        th.join();//等待10个线程结束
    }
    cout <<"count to "<<counter<<" successfully "<<endl;
    return 0;
}
//g++ demo1.cpp -o demo1 -l pthread

 

本文摘自 :https://www.cnblogs.com/


更多科技新闻 ......