使用等待对象的方法,实现多线程的同步处理。。

本文介绍如何在Windows环境下使用_beginthreadex创建线程,并通过互斥量进行线程间的同步处理。文中提供了完整的示例代码,展示了如何创建并管理多个线程,以及如何确保它们按预期顺序执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 #include <windows.h>


#include <process.h>   

/* _beginthread, _endthread */

这是一个创建线程的宏,必须在

工程->设置->C/C++->Code Generation->Use run-time libray->选 Debug Multithread(多线程),或 Multithread

才可以使用,不然会出现,没有定义的错误。。。


#include <stddef.h>
#include <stdio.h>
 

UINT WINAPI Thread_1(LPVOID para)
{
  HANDLE *handle = (HANDLE*)(para);
 WaitForSingleObject(*handle, INFINITE);
 printf("start_1/n");

 
 Sleep(2000);

 printf("end_1/n");

 ReleaseMutex(*handle);
 return 0;
}

UINT WINAPI Thread_2(LPVOID para)
{


 HANDLE *handle = (HANDLE*)(para);     //得到主函数中的线程的句柄


 WaitForSingleObject(*handle, INFINITE);   //等待对象,第二个参数表示,时间是无限的。。。


 printf("start_2/n");
 
 
 Sleep(2000);
 
 printf("end_2/n");
 ReleaseMutex(handle); 
 return 0;
}


int main()
{
 HANDLE handle = CreateMutex(NULL, FALSE, NULL);
 

//创建两个线程,得到他们的句柄。。。

//设置了线程的完成函数,第三个参数为传入完成函数的参数,和过滤驱动中的用法一样
 HANDLE handle_1 = (HANDLE)_beginthreadex(NULL, 0, Thread_1, &handle, 0, NULL);
 HANDLE handle_2 = (HANDLE)_beginthreadex(NULL, 0, Thread_2, &handle, 0, NULL);

 Sleep(6000);

 return 0;
}

 

Creates a thread.

uintptr_t _beginthread( 
   void( *start_address )( void * ),
   unsigned stack_size,
   void *arglist 
);
uintptr_t _beginthreadex( 
   void *security,
   unsigned stack_size,
   unsigned ( *start_address )( void * ),
   void *arglist,
   unsigned initflag,
   unsigned *thrdaddr 
);
//创建线程函数的说明

uintptr_t _beginthreadex(
   void * security,
   unsigned stack_size,
   unsigned ( * start_address )( void * ),
   void * arglist,
   unsigned initflag,
   unsigned * thrdaddr
);
如果上边的出现没有加入等待的处理,打印语句将混在一起。。。
uintptr_t _beginthread(
   void( * start_address )( void * ), 
   unsigned stack_size,
   void * arglist
);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值