thread应用示例

atomic介绍

  • #include
  • 对int、char、bool等数据结构进行原子封装,在多线程环境中,对std::atomic对象的访问不会造成竞争-冒险。利用st::atomic可实现数据结构的无锁设计
  • std::atomic对象的值的读取和写入使用load和store实现
  • 原子操作,取的是原子最小,不可分割的意义,它表示在多线程访问同一个全局资源时,能够确保所有其他的线程都不在同一时间内访问相同的资源。

线程

  • 语法1
thread my_thread{background_task()}
  • 语法2
thread my_thread((background_task()))
  • 语法3 lambda表达式
thread my_thread([]{
    do_something();
    do_something_else();
})
  • 线程结束

启动了线程,需要明确时要等待线程结束(加入joined),阻塞主线程。还是让其自主运行(分离detached)。

要在线程销毁之前加入或分离。

lambda

[capture list] (parameter list) -> return type{ function body },其中capture list(捕获列表)是lambda所在函数中定义的局部变量的列表(通常为空);return type、parameter list和function body 分别表示返回类型、函数列表和函数体。

隐式捕获

让编译器根据lambda体中的代码来推断我们要使用那些变量。在捕获列表中写一个&或=,&采用捕获引用,=采用值捕获。

设计程序1

程序设计两个线程,线程1通过终端将数据写入队列,线程2读取队列数据,进行加1处理,当终端输入100时,线程1停止写入数据,线程2停止加1操作。

#include<iostream>
#include<vector>
#include<atomic>
#include<queue>
#include<mutex>
#include<thread>

using namespace std;
atomic<bool> read(true);
queue<int> num;

void thread1()
{
        int temp;
        while(true){
                cin >> temp;
                if (temp == 100){
                        read.store(false);
                        cout << "quit" << endl;
                        break;
                }
                num.push(temp);
                if (num.empty()){
                        cerr << "num is empty" << endl;
                        break;
                }
        }
}

void thread2()
{
        cout << "it is thread2" << endl;
        while(true)
        {
                if(num.empty()){
                        if(read.load())
                        {
                                continue;
                        }
                        else
                        {
                                cout << "thread2 quit" << endl;
                                break;
  						}
                }
                else{
                //      int  add = num.front();
                        cout << num.front()  + 1 << endl;

                        num.pop();
                }
        }
}

int main()
{
        thread t1(&thread1);
        thread t2(&thread2);
        t1.join();
        t2.join();
        return 0;
}

当不使用read(true)时,线程2直接退出。

设计程序2

程序设计三个线程,队列数据设置成pair<int,int>,线程1通过终端将数据写入队列pair对象second成员,first设置成写入数据序号。线程2读取队列数据,将pair对象second成员进行加1处理,将加1后的pair写入优先队列,将当终端输入100时,线程1停止写入数据,线程2停止加1操作。当线程2结束,线程3读取降序排列的优先队列。

#include<iostream>
#include<vector>
#include<atomic>
#include<queue>
#include<mutex>
#include<thread>
#include<unistd.h>

using namespace std;
atomic<bool> read_flag(true);
atomic<bool> add(true);
typedef pair<int,int>   pairnum;
queue<pairnum> num;
priority_queue<pairnum,vector<pairnum>,less<pairnum>> show;

void thread1()
{
        int temp;
        int index = 0;
        while(true){
                cin >> temp;
                if (temp == 100){
                        read_flag.store(false);
                        cout << "quit" << endl;
                        break;
                }
                num.push(make_pair(index++,temp));
                if (num.empty()){
                        cerr << "num is empty" << endl;
                        break;
                }
        }
}

void thread2()
{
        cout << "it is thread2" << endl;
        while(true)
        {
                pair<int,int> num_copy;
                if(num.empty()){
                        if(read_flag.load())
                        {
                                continue;
                        }
                       cout << "thread2 quit" << endl;
                                break;
                        }
                }
                else{
                        num_copy = num.front();
                        num_copy.second +=1;
                        cout << num_copy.first << "," << num_copy.second  << endl;

                        num.pop();
                        show.push(num_copy);
                }
        }
        add.store(false);
}


void thread3()
{
        int i = 0;
        while(true)
        {
                if(show.empty())
                {
                        if(add.load() == 0)
                        {
                                cout << "thread3 is end" << endl;
                                break;
                        }
                        else
                                usleep(10000);
                }
                else if(i == show.top().first)
                {
                        cout << "show is " << show.top().first << "," << show.top().second   << endl;
                        i++;
                        show.pop();
                }

        }

}

int main()
{
        thread t1(thread1);
        thread t2(thread2);
        thread t3(thread3);
        t1.join();
        t2.join();
        t3.join();
        return 0;
}            

设计程序3

在程序2的基础上,加入一个线程4,该线程与线程2进行相同的操作。线程2和线程4操作num时需要加锁。

#include<iostream>
#include<vector>
#include<atomic>
#include<queue>
#include<mutex>
#include<thread>
#include<unistd.h>

using namespace std;
atomic<bool> read_flag(true);
atomic<bool> add(true);
typedef pair<int,int>   pairnum;
queue<pairnum> num;
mutex mtx_num;
priority_queue<pairnum,vector<pairnum>,less<pairnum>> show;

void thread1()
{
        int temp;
        int index = 0;
        while(true){
                cin >> temp;
                if (temp == 100){
                        read_flag.store(false);
                        cout << "quit" << endl;
                        break;
                }
                num.push(make_pair(index++,temp));
                if (num.empty()){
                        cerr << "num is empty" << endl;
                        break;
                }
        }
}


void thread3()
{
        //atomic<int> index_show(0);
        int i = 0;
        while(true)
        {
                if(show.empty())
                {
                        if(add.load() == 0)
                        {
                                cout << "thread3 is end" << endl;
                                break;
                        }
                         else
                                usleep(10000);
                }
        //      else if(index_show.load() == show.top().first)
                else if(i == show.top().first)
                {
                        cout << "show is " << show.top().first << "," << show.top().second   << endl;
                        //index_show++;
                        i++;
                        show.pop();
                }

        }

}

int main()
{
        vector<thread> threads;
        thread t1(thread1);
        for (int i = 0; i < 2; ++i)
        {
                threads.push_back(thread([&](){
                        while(true)
                        {
                                pair<int,int> num_copy;
                                mtx_num.lock();
                                if(num.empty()){
                                        mtx_num.unlock();
                                        if(read_flag.load())
                                        {
                                                continue;
                                        }
                                        else
                                        {
                                                cout << "thread2 quit" << endl;
                                                break;
                                        }
                                }
                                else{
                                        num_copy = num.front();
                                        num_copy.second +=1;
                                        cout << num_copy.first << "," << num_copy.second  << endl;
 num.pop();
                                        show.push(num_copy);
                                }
                                mtx_num.unlock();
                        }
                        add.store(false);
                }));
        }
        thread t3(thread3);
        t1.join();
        for(auto &t:threads)
                t.join();
        t3.join();
        return 0;
}

程序设计4

在程序3的基础上,修改线程1,将数据从终端输入改成,计数生成。

#include<iostream>
#include<vector>
#include<atomic>
#include<queue>
#include<mutex>
#include<thread>
#include<unistd.h>

using namespace std;
atomic<bool> read_flag(true);
atomic<int> add(2);
typedef pair<int,int>	pairnum;
queue<pairnum> num;
mutex mtx_num;
mutex mtx_show;
priority_queue<pairnum,vector<pairnum>,less<pairnum>> show;

void thread1()
{
	int temp = 0;
	int index = 0;
	while(true){
	//	cin >> temp;
		if (temp > 10){
			read_flag.store(false);
			cout << "quit" << endl;
			break;
		}
		else
			temp +=1;
		mtx_num.lock();
		num.push(make_pair(index++,temp));
		mtx_num.unlock();
		if (num.empty()){
			cerr << "num is empty" << endl;
			break;
		}
	}	
}


void thread3()
{
	//atomic<int> index_show(0);
	int i = 10;
	cout << "it is thread3" << endl;
	while(true)
	{
		mtx_show.lock();
		if(show.empty())
		{
			mtx_show.unlock();
			if(add.load() == 0)
			{
				cout << "thread3 is end" << endl;
				break;
			}
			else
				usleep(10000);
		}
	//	else if(index_show.load() == show.top().first)
		else if(i == show.top().first)
		{
			cout << "show is " << show.top().first << "," << show.top().second   << endl;
			//index_show++;
			i--;
			show.pop();
			mtx_show.unlock();
		}
		else
			mtx_show.unlock();

					

	}
		
}

int main()
{
	vector<thread> threads;
	thread t1(thread1);
	for (int i = 0; i < 2; ++i)
	{
		threads.push_back(thread([&](){
			while(true)
			{
				pair<int,int> num_copy;
				mtx_num.lock();
				if(num.empty()){
					mtx_num.unlock();
					if(read_flag.load())
					{
						continue;
					}
					else
					{
						cout << "thread2 quit" << endl;
						break;	
					}
				}
				else{
					num_copy = num.front();
					num_copy.second +=1;
					cout << num_copy.first << "," << num_copy.second  << endl;
					
					num.pop();
					mtx_show.lock();
					show.push(num_copy);
					mtx_show.unlock();
				}
				mtx_num.unlock();		
			}
			add--;
		}));
	}
	thread t3(thread3);
	t1.join();
	for(auto &t:threads)
		t.join();
	t3.join();
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

硬码农二毛哥

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

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

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

打赏作者

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

抵扣说明:

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

余额充值