如何创建启动一个线程
std::thread创建一个线程对象,传入线程所需要的的线程函数和参数,线程自动开始执行。
void threadHandle1()
{
//子线程等待两秒
std::this_thread::sleep_for(std::chrono::seconds(2));
cout << "hello thread1" << endl;
}
int main()
{
//定义了一个线程对象 传入一个线程函数 新线程开始运行
std::thread t1(threadHandle1);
//主线程等待子线程结束 主线程继续
//t1.join();
//把子线程设置为分离线程
t1.detach();
cout << "main thread" << endl;
return 0;
}
通过加锁来解决多线程问题
static int count = 100;
std::mutex tex; //互斥锁
void sellTicket(int index)
{
while (::count > 0) //count==1 锁+双重判断
{
tex.lock();
if (::count > 0)
{
cout << "chuangkou" << index << "卖出" << ::count << endl;
//cout << ::count << endl;
::count--;
}
tex.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main()
{
list<std::thread> t;
for (int i = 0; i < 3; i++)
{
t.push_back(s

本文详细介绍了C++中如何创建和启动线程,通过加锁机制解决多线程同步问题,探讨了生产者与消费者的经典场景,并比较了unique_lock和lock_guard在互斥操作中的应用。
最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



