C++ 2个子线程通过 CreateSemaphore函数同步数据
时间: 2024-09-06 19:05:30 浏览: 74
在C++中,你可以使用`CreateSemaphore`函数结合Windows API来同步两个子线程的数据。`CreateSemaphore`函数允许你在并发环境中管理访问共享资源的权限,比如控制线程的执行顺序。
下面是一个简单的示例,展示了如何创建一个互斥信号量(mutex)并用于两个子线程之间的同步:
```cpp
#include <windows.h>
#include <iostream>
// 创建一个互斥信号量
HANDLE semaphore = CreateSemaphore(NULL, // default security attributes
0, // initial count (0表示开始时为未释放状态)
MAX_SEMAPHORE_COUNT, // maximum count (可以设置为任意值)
L"YourSemaphoreName"); // 名称,便于管理和识别
void thread_function1() {
while (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) { // 等待信号量变为可用
std::cout << "Thread 1 waiting..." << std::endl;
}
// 在这里处理数据...
ReleaseSemaphore(semaphore, 1, NULL); // 数据处理完毕,释放信号量
}
void thread_function2() {
while (WaitForSingleObject(semaphore, INFINITE) != WAIT_OBJECT_0) { // 等待信号量变为可用
std::cout << "Thread 2 waiting..." << std::endl;
}
// 同样的,在这里处理数据...
ReleaseSemaphore(semaphore, 1, NULL);
}
int main() {
HANDLE threads[2];
for (size_t i = 0; i < 2; ++i) {
threads[i] = CreateThread(NULL, 0, &thread_function1, NULL, 0, NULL);
if (!threads[i]) {
std::cerr << "Failed to create thread " << i << std::endl;
return -1;
}
}
// 等待所有线程完成
for (size_t i = 0; i < 2; ++i) {
WaitForSingleObject(threads[i], INFINITE);
CloseHandle(threads[i]);
}
CloseHandle(semaphore);
return 0;
}
阅读全文
相关推荐




















