C++ Thread操作

C++ Thread操作

// thread Operation
//

#include "stdafx.h"
#include<iostream>
#include<thread>
#include <Windows.h>
#include<mutex>
using namespace std;
#define takeNum(n) printf("num_"#n"=%d",num_##n);
int count12 = 24;
int num_12 = 24;
mutex m;  //定义mutex

void t1();
void t2();

int _tmain(int argc, _TCHAR* argv[])
{
	//cout << 1 << endl;
	thread th1(t1);
	thread th2(t2);
	cout << th1.joinable() << endl;
	th1.join();//该线程停止主线程才会退出
	th2.detach();//detach线程对象与线程分离,线程对象不能对线程做控制,线程对象释放不会影响线程的继续执行,但主线程推出线程会停止
	cout << th1.joinable() << endl;  
	takeNum(12);
	char c;
	cin >> c;
	return 0;
}




void t1(){

	for (int i = 0; i < 20; i++){
		//m.lock();  //上锁
		lock_guard<mutex> lockGuard(m);  //可以防止程序异常退出,不能unlock,可以自动释放锁
		//cout << i << "!" << endl;
		//m.unlock(); //释放锁
	}
}

void t2(){
	for (int i = 0; i < 10; i++){
		//m.lock();  //上锁
		lock_guard<mutex> lockGuard(m);
		//cout << i << "@" << endl;
		//m.unlock();  //释放锁
	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值