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;
}
相关推荐
iCxhust27 分钟前
windows环境下在Bochs中运行Linux0.12系统
linux·运维·服务器·windows·minix
上去我就QWER1 小时前
Qt中如何获取系统版本信息
开发语言·qt
我是苏苏2 小时前
C#高级:程序查询写法性能优化提升策略(附带Gzip算法示例)
开发语言·算法·c#
木木子99992 小时前
业务架构、应用架构、数据架构、技术架构
java·开发语言·架构
大佬,救命!!!7 小时前
C++多线程同步与互斥
开发语言·c++·学习笔记·多线程·互斥锁·同步与互斥·死锁和避免策略
赵文宇(温玉)8 小时前
构建内网离线的“github.com“,完美解决内网Go开发依赖
开发语言·golang·github
qq7422349848 小时前
Python操作数据库之pyodbc
开发语言·数据库·python
Joker100858 小时前
仓颉自定义序列化:从原理到高性能多协议实现
开发语言
Adellle8 小时前
2.单例模式
java·开发语言·单例模式
散峰而望8 小时前
C++入门(一)(算法竞赛)
c语言·开发语言·c++·编辑器·github