• C++ 中的多线程


    在VS2015中,创建多线程很方便,只需要引入相应的头文件即可

    其中 #include <thread> 为多线程需要的头文件。

    引入头文件后,即可创建子线程进行耗时操作了。

    当然,为了防止变量共享带来的问题,可以加入互斥操作,这时需要引入相应的互斥操作的头文件,如:mutex。

    关于多线程的互斥,可以参考:http://www.cnblogs.com/haippy/p/3237213.html 写的很详细。

    一个简单的例子:

    //C++ 多线程示例

    #include "stdafx.h"
    #include <iostream>
    #include <string>
    #include <thread>
    #include <mutex>
    using namespace std;


    mutex mutx;

    //一个全局函数,将会在线程中调用
    void printHreadInfro(int id,string par) {
        //mutx.lock();
        if (mutx.try_lock())
        {
            cout << endl << "used by thread :" << id << ";Par =" << par << endl;
            mutx.unlock();
        }
        //mutx.unlock();
    }
    void sayHello(string par) {

        for (int i = 0; i < 1000; i++)
        {
            printHreadInfro(101,par);
        }
    }
    void sayHello_2(string par)
    {
        for (int i = 0; i < 1000; i++)
        {
            printHreadInfro(2001,par);
        }
    }
    int main()
    {
        thread th1(sayHello,"par in id1");    //定义线程时可以给回调函数传递任意多的任意类型的参数(定义函数时的参数列表)
        th1.join();                    //通过join阻塞线程,直到该线程结束
        thread th2(sayHello_2,"hello, i'm from thread 2");
        th2.detach();                //如果可分离,则可以用 detach 将子线程与主线程分离

        string s;
        getline(cin, s, '\n');
        return 0;
    }

    由于使用 th1.join()使线程阻塞,只有当th1执行完毕后,才会往下继续执行,此时可以不考虑互斥问题,但如果不阻塞线程1、2,则需要考虑互斥问题。

  • 相关阅读:
    怎么查看这个历史最大连接session数
    16G 手机清理
    维骨力Glucosamine的最关键的几点...
    转 OGG Troubleshooting-Database error 1 (ORA-00001: unique constraint ...)
    Steps to Resolve the Database JAVAVM Component if it Becomes INVALID After Applying an OJVM Patch
    数据库sql 使用 lag 和OVER 函数和 like 使用 小技巧
    log file sync
    转 多个版本的数据库在同一服务器上ORA-12557
    datapatch meet ORA-01422
    运维题目(七)
  • 原文地址:https://www.cnblogs.com/xtblog/p/5738648.html
Copyright © 2020-2023  润新知