C++11 thread学习

本文详细介绍了C++中使用`std::thread`进行线程编程的各种方式,包括在main函数中调用普通函数和类成员函数,使用lambda表达式创建线程,以及线程同步与互斥访问。示例代码涵盖了无参、有参及静态成员函数的线程调用,并展示了如何在类中声明线程成员。同时,通过`std::mutex`演示了线程间的同步操作,确保对共享资源的安全访问。
摘要由CSDN通过智能技术生成

学习目标:

1.main函数里使用thread,调用普通函数

2.main函数里使用thread,调用class中的函数

3.在class中声明thread成员,调用class中线程函数

4.结合lamda表达式,使用thread

5.不同thread间,线程同步、互斥访问

6.线程优先级如何设置?

7.thread_pool实现

目标1:main函数里使用thread,调用普通函数

        main函数中,启动thread调用全局函数,

  •         无参:void ThreadFun();
  •         有参:void ThreadFunParam(int i,int j,char* pszArr);

                代码如下:

// thread example
#include <iostream>       // std::cout
#include <thread>         // std::threa

void ThreadFun()
{
	// do stuff...
	std::cout << "ThreadFun running" << std::endl;
}
void ThreadFunParam(int i,int j,char* pszArr)
{
	std::cout << "ThreadFunParam running" << std::endl;
	std::cout << "i:" << i << ",j:" << j << std::endl;
	if (nullptr != pszArr)
	{
		std::cout << "pszArr:" << pszArr << std::endl;
	}
	else
	{
		std::cout << "pszArr is nullptr"  << std::endl;
	}	
}

int main()
{
	std::thread first(ThreadFun);     // spawn new thread that calls ThreadFun()

	char szArr[100] = "hello thread world!";
	std::thread secondThread(ThreadFunParam, 10, 20,szArr);// spawn new thread that calls ThreadFunParam()

	std::cout << "main, foo and bar now execute concurrently...\n";

	// synchronize threads:
	first.join();                // pauses until first finishes
	secondThread.join();

	std::cout << "Thread completed.\n";
	return 0;
}

目标2:main函数里使用thread,调用class中的函数

main函数中启动thread,调用class中的函数

  •         无参:void foo() 
  •         有参:void funParam(int i)
  •         静态有参:static void funStatic(int i) 
#include <thread>
#include <iostream>

class bar {
public:
    void foo() {
        std::cout << "hello from member function" << std::endl;
    }
    void funParam(int i)
    {
        std::cout << "funParam fun start,i:"<<i << std::endl;
    }
    static void funStatic(int i)
    {
        std::cout << "funStatic fun start,i:" << i << std::endl;
    }
};

int main()
{
    std::thread t(&bar::foo, bar());
    t.join();

    std::thread t2(&bar::funParam, bar(), 10);
    t2.join();

    std::thread t3(bar::funStatic, 10);
    t3.join();
   
    std::cout << "main end" << std::endl;
    return 0;
}

目标3:在class中声明thread成员,调用class中线程函数

  • 无参:   void foo()
  • 有参:    void funParam(int i)
  • 静态有参:    static void funStatic(int i)
#include <thread>
#include <iostream>

class bar {
public:
    bar()
    {
        pt3 = nullptr;
    }
    //~bar()
    //{
    //   /* if (nullptr != pt3)
    //    {
    //        delete pt3;
    //        pt3 = nullptr;
    //    }*/
    //}
    void foo() {
        std::cout << "foo fun running" << std::endl;
    }
    void funParam(int i)
    {
        std::cout << "funParam fun start,i:" << i << std::endl;
    }
    static void funStatic(int i)
    {
        std::cout << "funStatic fun start,i:" << i << std::endl;
    }

    void startThread3()
    {
        pt3 = new std::thread(funStatic,30);
        pt3->join();
        //pt3->detach();
    }
    std::thread* pt3;

    void startThread2()
    {
        t2 = std::thread(&bar::foo, bar());
        t2.join();
        //t2.detach();
    }
    std::thread t2;

    void startThread()
    {
        t1 = std::thread(funStatic, 20);
        t1.join();
    }
    std::thread t1;
};

int main()
{
    {
        bar b1;
        b1.startThread();
        b1.startThread2();
        b1.startThread3();
    }

    std::cout << "main end" << std::endl;
    return 0;
}

目标5:不同thread间,线程同步、互斥访问

使用std::mutex

#include <iostream>
#include <thread>
#include <mutex>
int i = 0;
std::mutex m;

void threadFun()
{
	std::lock_guard<std::mutex> locker(m);
	//m.lock();
	i++;
	std::cout << "threadFun:" << i << ",this_threadid:"<<std::this_thread::get_id() << std::endl;
	//m.unlock();
}

int main()
{
	
	std::thread t[10];
	for (int j = 0; j < 10; j++)
	{
		t[j] = std::thread(threadFun);
	}

	for (int j = 0; j < 10; j++)
	{
		t[j].join();
	}

	return 0;
}

在C++中,创建线程的方式有多种方法。一种常见的方式是使用函数指针来创建线程。可以使用std::thread类来创建线程对象,并将函数指针作为参数传递给std::thread的构造函数。例如,可以使用以下代码创建一个线程对象并开启一个线程: ``` #include <cstdio> #include <thread> void fun(int a) { printf("%d\n", a); } int main() { int a = 1; std::thread t(fun, a); t.join(); return 0; } ``` 另一种方式是使用函数对象来创建线程。可以定义一个类,并重载该类的operator()()运算符,将该类的对象作为参数传递给std::thread的构造函数。例如,可以使用以下代码创建一个线程对象并开启一个线程: ``` #include <iostream> #include <thread> #include <chrono> using namespace std; class Thread_Test { public: void operator()() { for (int i = 0; i < 10; i++) { cout << "Thread_Test is running..." << endl; std::this_thread::sleep_for(std::chrono::seconds(1)); } } }; int main() { thread threadobj((Thread_Test())); cout << "main Thread is running..." << endl; threadobj.join(); cout << "exit from main Thread" << endl; return 0; } ``` 此外,还可以使用lambda函数来创建线程。可以定义一个lambda函数,并将其作为参数传递给std::thread的构造函数。例如,可以使用以下代码创建一个线程对象并开启一个线程: ``` #include <iostream> #include <thread> int main() { int a = 1; std::thread t([&a]() { std::cout << a << std::endl; }); t.join(); return 0; } ``` 总结起来,C++中创建线程的方式包括使用函数指针、函数对象和lambda函数。具体选择哪种方式取决于实际需求和个人偏好。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [C++创建线程的三种方式](https://blog.csdn.net/yangcunbiao/article/details/131151630)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [c++ 学习之 多线程(一) thread对象的创建](https://blog.csdn.net/weixin_45074185/article/details/104363741)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿土有品

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值