在类中实现线程

这篇博客介绍了如何在C++中于类内部创建和管理线程,通过类的成员函数实现线程的启动和同步,展示了线程安全地修改共享数据的例子。
摘要由CSDN通过智能技术生成

在类中实现线程的创建和调用

一般人都是在主函数中创建线程,但在类中创建线程并实现的比较少,记录于此备忘。
头文件#include “thread_test.h”
#pragma once

#include <stdio.h>
#include <stdlib.h>
#include // std::cout
#include // std::thread
using namespace std;
class threadTestTemp
{
public:
threadTestTemp() :switchTest(true), numberTest(256)
{

}
~threadTestTemp()
{};
bool switchTest;
int numberTest;

};
//
//class threadTest
//{
//public:
// threadTest();
// ~threadTest();
// void _threadSon(threadTestTemp* set);
// void createSonThread(threadTestTemp* set);
//};

class MyTest
{
public:
bool Bool_Step = true;
int tickets = 20;
MyTest::MyTest();
MyTest::~MyTest();
void MyTest::SellThread1(char* param);
void MyTest::SellThread2(threadTestTemp* set, char* param);
void My_Thread1(char* param);
void My_Thread2(threadTestTemp* set);
};

主文件
.cpp
#include<process.h>
#include<windows.h>
#include <stdio.h>
#include
#include
#include “thread_test.h”

using namespace std;

//

MyTest::MyTest()
{
}
MyTest::~MyTest()
{
}


void  MyTest::SellThread1(char* param)
{
	printf("第一个线程\n");
	char  *name = (char *)param;
	while (tickets > 0)
	{
		Sleep(100);
		if (Bool_Step)
		{
			//CPU恰好执行到这里,这个时候线程时间片到了,并且此时还剩最后一张票
			printf("%s卖出第%d张票!\n", name, tickets--);
			Bool_Step = false;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值