#include "stdafx.h" #include <windows.h> #include <process.h> #include <iostream> #include <fstream> using namespace std; void ThreadFunc1(PVOID param) { while(1) { Sleep(1000); cout<<"This is ThreadFunc1"<<endl; } } void ThreadFunc2(PVOID param) { while(1) { Sleep(1000); cout<<"This is ThreadFunc2"<<endl; } } int main() { int i=0; _beginthread(ThreadFunc1,0,NULL); _beginthread(ThreadFunc2,0,NULL); Sleep(3000); cout<<"end"<<endl; cin>>i; return 0; }实现顺序输出This is ThreadFunc1,This is ThreadFunc1
时间: 2024-02-07 13:02:51 浏览: 129
与This is ThreadFunc2交替输出的功能,可以使用互斥锁来实现线程同步。代码如下:
#include "stdafx.h"
#include <windows.h>
#include <process.h>
#include <iostream>
#include <fstream>
using namespace std;
HANDLE Mutex;
void ThreadFunc1(PVOID param) {
while(1)
{
WaitForSingleObject(Mutex,INFINITE); // 等待互斥锁
cout<<"This is ThreadFunc1"<<endl;
ReleaseMutex(Mutex); // 释放互斥锁
Sleep(1000);
}
}
void ThreadFunc2(PVOID param) {
while(1)
{
WaitForSingleObject(Mutex,INFINITE); // 等待互斥锁
cout<<"This is ThreadFunc2"<<endl;
ReleaseMutex(Mutex); // 释放互斥锁
Sleep(1000);
}
}
int main() {
int i=0;
Mutex = CreateMutex(NULL,FALSE,NULL); // 创建互斥锁
_beginthread(ThreadFunc1,0,NULL);
_beginthread(ThreadFunc2,0,NULL);
Sleep(3000);
cout<<"end"<<endl;
cin>>i;
CloseHandle(Mutex); // 关闭互斥锁句柄
return 0;
}
在这个程序中,创建了一个互斥锁对象Mutex,然后在ThreadFunc1和ThreadFunc2中使用WaitForSingleObject和ReleaseMutex来实现对Mutex的加锁和解锁操作,从而保证了两个线程输出的互斥性。
阅读全文