C 语言 windows 多线程示例

在这个代码中,我们使用了 CreateThread 函数来创建线程,WaitForMultipleObjects 函数来等待所有线程完成,CloseHandle 函数来关闭线程句柄。Sleep 函数用于模拟线程工作时的延迟。

cpp 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

// 线程函数
DWORD WINAPI thread_function(LPVOID arg) {
	int thread_id = *(int*)arg;

	printf("Thread %d is running.\n", thread_id);

	// 模拟线程工作
	for (int i = 0; i < 5; i++) {
		printf("Thread %d is working: %d\n", thread_id, i);
		Sleep(1000);  // 模拟工作延迟
	}

	printf("Thread %d has finished working.\n", thread_id);

	return 0;
}

int main() {
	// 创建线程
	HANDLE threads[2];
	int thread_ids[2] = { 1, 2 };

	for (int i = 0; i < 2; i++) {
		threads[i] = CreateThread(
			NULL,                   // 默认安全属性
			0,                      // 默认堆栈大小
			thread_function,        // 线程函数
			&thread_ids[i],         // 线程参数
			0,                      // 默认创建标志
			NULL                    // 不需要线程ID
		);

		if (threads[i] == NULL) {
			printf("Error creating thread %d\n", thread_ids[i]);
			return 1;
		}
	}

	// 等待线程完成
	WaitForMultipleObjects(2, threads, TRUE, INFINITE);

	// 关闭线程句柄
	for (int i = 0; i < 2; i++) {
		CloseHandle(threads[i]);
	}

	printf("All threads have finished.\n");

	return 0;
}
相关推荐
云樱梦海11 分钟前
OpenClaw官方:OpenClaw Windows Node 实战(1.5K ★ 开源推荐)
windows·开源·github·openclaw
人道领域13 分钟前
【LeetCode刷题日记】131.分割回文串,动态规划优化
java·开发语言·leetcode
z落落25 分钟前
C# 接口 interface (多接口实现、类+接口、成员重名)
java·开发语言
深度学习04071 小时前
SVN 独立服务端部署与客户端使用指南(CentOS/Rocky 9.5 + Windows)
windows·svn
爱分享软件的学长1 小时前
Tiled Map Editor 1.12.1 官方版下载(夸克网盘+百度网盘,SHA256校验)
windows·开源软件·软件下载
知识的宝藏2 小时前
Xpaht self::div 轴语法
开发语言
keykey6.2 小时前
卷积神经网络(CNN):让AI学会“看“
开发语言·人工智能·深度学习·机器学习
ss2732 小时前
【入门OJ题解】分苹果问题(Python/Java/C 实现)
java·c语言·python
IsJunJianXin2 小时前
谷歌搜索cookie NID逆向生成
开发语言·python·google搜索·sgss·nid-cookie·算法生成nid·google-cookie
Dream-Y.ocean2 小时前
鸿蒙PC平台 Carnac 按键显示适配实战:从 Windows 到 HarmonyOS 的 Electron 迁移指南
windows·electron·harmonyos