记录:c++创建线程

1.简单记录

#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
#include <thread>
#include <unistd.h>
using namespace std;

void pthread1() 
{ 
	while(1){
		cout << "aaaaaaaaaa\n";
		sleep(1);
	}
} 
void pthread2() 
{ 
	while(1){
		cout << "bbbbbbbbbbbb\n";
		sleep(1);
	}
}

int main(int argc, char** argv)
{
	thread t1(pthread1);    
	thread t2(pthread2);	
	t1.join();
	t2.join();
	return 0;
}

2.对象

#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
#include <thread>
#include <unistd.h>
using namespace std;

class my_thread{
public:
	my_thread()
	{
		thread t(bind(&my_thread::my_run, this, "zbyyy"));    
		t.join();
	}
private:
	void my_run(const char *name);
};

void my_thread::my_run(const char *name)
{
	while(1){
		cout << "----%s\n" << name;
		sleep(1);
	}
}

int main(int argc, char** argv)
{
	my_thread my_t;
	return 0;
}


END!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
线程修改sleep的一个常见方法是使用条件变量来控制线程的执行顺序。通过引入一个状态变量和两个条件变量,可以实现线程之间的同步和顺序执行。具体步骤如下: 1. 定义一个互斥锁mutex和两个条件变量cv_1、cv_2。 2. 定义一个静态变量point来记录线程间的状态。 3. 在add函数中,线程1通过互斥锁获取锁资源,并在状态为0时执行相应的操作。如果point的值能够被5整除,则修改状态为1,并唤醒等待在cv_1上的线程2。 4. 在print函数中,线程2通过互斥锁获取锁资源,并在状态为1时执行相应的操作。输出point的值后,修改状态为0,并唤醒等待在cv_1上的线程1。 5. 在主函数中创建两个线程t1和t2,并分别执行add和print函数。等待两个线程执行完毕后退出。 代码示例: ```c #include <iostream> #include <thread> #include <mutex> #include <condition_variable> using namespace std; mutex mt; condition_variable cv_1; static int point = 0; int status = 0; void add() { int times = 100; while (times--) { unique_lock<mutex> lk(mt); while (status != 0) { cv_1.wait(lk); } point++; if (point % 5 == 0) { status = 1; cv_1.notify_one(); } } } void print() { int times = 100 / 5; while (times--) { unique_lock<mutex> lk(mt); while (status != 1) { cv_1.wait(lk); } cout << "point: " << point << endl; status = 0; cv_1.notify_one(); } } int main() { thread t1 = thread(add); thread t2 = thread(print); t1.join(); t2.join(); return 0; } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值