【多线程】两个线程 交替执行

本文介绍了一个使用Windows API实现的线程交替输出示例,通过互斥量控制两个或多个线程间的交替打印字符,展示了如何利用`CreateThread`、`CreateMutex`、`WaitForSingleObject`和`ReleaseMutex`等函数实现线程同步。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <windows.h>

using namespace std;
HANDLE hMutex;

DWORD WINAPI Fun(LPVOID lpParamter)
{
    while(1)
	{
		WaitForSingleObject(hMutex, INFINITE);
		cout<<"A"<<endl; 
		Sleep(1000);
		ReleaseMutex(hMutex);
    }
	return 0;
}

DWORD WINAPI Fun1(LPVOID lpParamter)
{
	while(1) 
	{ 
		 WaitForSingleObject(hMutex, INFINITE);
		 cout<<"B"<<endl; 
		 Sleep(1000);
		 ReleaseMutex(hMutex);
	}
	return 0;
}

int main()
{
	HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);
	hMutex = CreateMutex(NULL, FALSE, (LPWSTR)"screen");
	CloseHandle(hThread);

	HANDLE hThread1 = CreateThread(NULL, 0, Fun1, NULL, 0, NULL);
	CloseHandle(hThread1);
	
	while(1);
	return 0;
}


以上是两个子线程之间交替。主线程闲着。

 

下面是主线程和一个子线程之间交替

#include <iostream>
#include <windows.h>
using namespace std;
HANDLE hMutex;
DWORD WINAPI Fun(LPVOID lpParamter)
{
	while(1) 
	{ 
		 WaitForSingleObject(hMutex, INFINITE);
		 Sleep(1000);
		 cout<<"Fun display!"<<endl;
		 ReleaseMutex(hMutex);
	}
}

int main()
{
	HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);
	hMutex = CreateMutex(NULL, FALSE, (LPWSTR)"screen");
	CloseHandle(hThread);
	while(1) 
	{
	   WaitForSingleObject(hMutex, INFINITE);
	   Sleep(1000);
	   cout<<"main display!"<<endl;
	   ReleaseMutex(hMutex);
	}
	return 0;
}


 各位大神,如果我想只输出10次呢?怎么改呢?

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值