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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章