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;
}
相关推荐
Pocker_Spades_A22 分钟前
Python快速入门专业版(二十六):Python函数基础:定义、调用与返回值(Hello函数案例)
开发语言·python
island131430 分钟前
【C++框架#5】Elasticsearch 安装和使用
开发语言·c++·elasticsearch
周周记笔记1 小时前
学习笔记:Python的起源
开发语言·python
Cachel wood1 小时前
信息检索、推荐系统模型排序质量指标:AP@K和MAP@K
windows·搜索引擎·json·推荐系统·搜索
懒大王95271 小时前
uni-app + Vue3 + EZUIKit.js 播放视频流
开发语言·javascript·uni-app
_extraordinary_1 小时前
Java 多线程进阶(四)-- 锁策略,CAS,synchronized的原理,JUC当中常见的类
java·开发语言
_假正经1 小时前
Windows下使用PerfMon进行性能监控并记录日志
windows
JasmineX-11 小时前
数据结构——顺序表(c语言笔记)
c语言·开发语言·数据结构·笔记
Source.Liu1 小时前
【Pywinauto库】10.7 pywinauto.controls.uia_controls控件
windows·python·自动化
小六子成长记1 小时前
【C++】:list容器全面解析(超详细)
c++·windows·list