1. C++11 啓動一個線程

C++11 中引入了 thread 庫,只需要在頭文件中包含 #include<thread>即可。創建一個線程可以有多種方式,可以使用函數、仿函數、lambda表達式、類成員函數。

1.使用函數


#include <iostream>
#include <thread>

void f1()
{
	printf("hello liuyang\n");
}

void f2(int a)
{
	printf("a = %d\n", a);
}

int main()
{
	std::thread t1(f1);
	std::thread t2(f2, 1); // 有參數直接加在後面

	t1.join(); // 等待線程退出
	t2.join();
	
	getchar();
	return 0;
}

2. 仿函數

仿函數有一點需要注意,如下面示例中,在std::thread傳遞不帶參數的仿函數,默認會當成聲明,不會啓動線程。
解決辦法:用()將仿函數括起來,或者初始化用{},如下面示例所示

#include <iostream>
#include <thread>

struct mystruct
{
    void operator()()
    {
        printf("hello mystruct\n");
    }
    void operator()(int a, int b)
    {
        printf("a + b = %d\n", a + b);
    }
};

int main()
{
	std::thread t1(mystruct());  // 會被當成聲明
    std::thread t2((mystruct()));// ok
    std::thread t3{mystruct()};  // ok
    std::thread t4(mystruct(), 1, 2);  // 有參數的不會被當成聲明
    // t1.join();

    getchar();
    return 0;
}

3. lambda表達式

#include <iostream>
#include <thread>

int main()
{
	std::thread t1([](){printf("hello world\n");});
	std::thread t2([](int a, int b){printf("a+b=%d\n", a, b);}, 3, 4);
	

	getchar();
	return 0;
}

4. 類成員函數

#include <iostream>
#include <thread>

class myclass
{
public:
    void func(int a)
    {
        printf("hello, %d\n", a);
    }
};

int main()
{
    myclass c;

    std::thread t1(&myclass::func, &c, 1000);
    
    getchar();
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章