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;
}
相关推荐
杜小暑32 分钟前
动态内存管理
c语言·开发语言·动态内存管理
想不明白的过度思考者34 分钟前
Java从入门到“放弃”(精通)之旅——JavaSE终篇(异常)
java·开发语言
YuforiaCode1 小时前
第十二届蓝桥杯 2021 C/C++组 直线
c语言·c++·蓝桥杯
我真的不会C1 小时前
QT窗口相关控件及其属性
开发语言·qt
CodeCraft Studio1 小时前
Excel处理控件Aspose.Cells教程:使用 Python 在 Excel 中进行数据验
开发语言·python·excel
火柴盒zhang1 小时前
websheet之 编辑器
开发语言·前端·javascript·编辑器·spreadsheet·websheet
子非衣1 小时前
Windows云主机远程连接提示“出现了内部错误”
服务器·windows
景天科技苑1 小时前
【Rust】Rust中的枚举与模式匹配,原理解析与应用实战
开发语言·后端·rust·match·enum·枚举与模式匹配·rust枚举与模式匹配
阿让啊1 小时前
C语言中操作字节的某一位
c语言·开发语言·数据结构·单片机·算法
椰羊~王小美1 小时前
LeetCode -- Flora -- edit 2025-04-25
java·开发语言