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;
}
相关推荐
CodeWithMe8 分钟前
【C/C++】namespace + macro混用场景
c语言·开发语言·c++
蓝婷儿16 分钟前
6个月Python学习计划 Day 17 - 继承、多态与魔术方法
开发语言·python·学习
Mikhail_G40 分钟前
Python应用变量与数据类型
大数据·运维·开发语言·python·数据分析
YuTaoShao1 小时前
Java八股文——集合「List篇」
java·开发语言·list
Bl_a_ck1 小时前
【JS进阶】ES6 实现继承的方式
开发语言·前端·javascript
愈努力俞幸运2 小时前
c++ 头文件
开发语言·c++
永日456702 小时前
学习日记-day24-6.8
开发语言·学习·php
BillKu2 小时前
Java后端检查空条件查询
java·开发语言
十五年专注C++开发2 小时前
CMake基础:gcc/g++编译选项详解
开发语言·c++·gcc·g++
SY师弟2 小时前
台湾TEMI协会竞赛——0、竞赛介绍及开发板介绍
c语言·单片机·嵌入式硬件·嵌入式·台湾temi协会