多线程编程Demo[利用事件对象实现线程同步]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Windows C多线程编程Demo可以通过使用Windows API来实现。以下是一个简单的例子: ```c #include <stdio.h> #include <windows.h> DWORD WINAPI ThreadFunc(LPVOID lpParam) { int thread_num = *((int*)lpParam); printf("Thread %d is running\n", thread_num); Sleep(1000); // 模拟线程执行的一些操作 printf("Thread %d is done\n", thread_num); return 0; } int main() { const int num_threads = 3; HANDLE threads[num_threads]; int thread_nums[num_threads]; for (int i = 0; i < num_threads; ++i) { thread_nums[i] = i; threads[i] = CreateThread(NULL, 0, ThreadFunc, &thread_nums[i], 0, NULL); if (threads[i] == NULL) { fprintf(stderr, "Error creating thread\n"); return 1; } } WaitForMultipleObjects(num_threads, threads, TRUE, INFINITE); // 等待所有线程执行完毕 for (int i = 0; i < num_threads; ++i) { CloseHandle(threads[i]); // 关闭线程句柄 } return 0; } ``` 上述代码创建了3个线程,并使用CreateThread函数创建了每个线程。每个线程执行相同的ThreadFunc函数,该函数简单地输出线程号,并模拟一些操作。主线程使用WaitForMultipleObjects函数等待所有线程执行完毕。最后,必须关闭每个线程句柄来释放资源。 这只是一个简单的多线程编程示例,在实际应用中,可能需要更复杂的线程同步和线程间通信机制,比如互斥量、信号量等。通过使用Windows API,我们可以实现更复杂和高效的多线程应用程序。 ### 回答2: Windows下的C语言多线程编程可以通过使用Windows API中提供的相关函数来实现。常用的函数包括`CreateThread`创建线程、`WaitForSingleObject`等待线程运行结束、`CloseHandle`关闭线程句柄等。 以下是一个简单的Windows C多线程编程的示例程序: ```c #include <stdio.h> #include <windows.h> DWORD WINAPI MyThreadFunc(LPVOID lpParam) { int i; for (i = 0; i < 5; i++) { printf("Thread is running: %d\n", i); Sleep(1000); // 线程休眠1秒 } return 0; } int main() { HANDLE hThread; DWORD dwThread; // 创建线程 hThread = CreateThread(NULL, 0, MyThreadFunc, NULL, 0, &dwThread); if (hThread == NULL) { printf("Failed to create thread.\n"); return 1; } printf("Main thread is running.\n"); // 等待线程结束 WaitForSingleObject(hThread, INFINITE); printf("Main thread is exiting.\n"); // 关闭线程句柄 CloseHandle(hThread); return 0; } ``` 该示例程序创建了一个新线程,新线程运行`MyThreadFunc`函数,该函数会打印5次当前运行次数,并休眠1秒。主线程输出一条信息后,使用`WaitForSingleObject`等待新线程运行结束,然后输出退出信息。 以上就是一个简单的Windows C多线程编程示例。在实际开发中,可以结合具体需求使用多线程来提升程序的并发性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值