安全的使用CreateThread()

这个示例使用多个线程在当前目录下搜索.c文件,寻找命令行中给出的字符串。为了避免使用多线程C运行时库,它使用了临界区来确保屏幕输出不被交错。正常情况下,如果使用printf(),多线程C运行时会自动处理这个问题。

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

/*uses multiple threads to search the files
".c" in the current directory for the string given
on th command line;
this example avoids most C run-time functions,so
that it can use the single-thread Clibraries,
it is necessary to use a critical section to divvy 
up output to the screen or the various threads end up 
with their output intermingled .Normally the multithreaded 
C run-time does this automatically if you use printf*/


#include<Windows.h>
#include "MtVerify.h"


DWORD WINAPI SearchProc(void *arg);
BOOL GetLine(HANDLE hFile, LPSTR buf, DWORD size);
#define MAX_THREADS 3
HANDLE hThreadLimitSemaphore;
HANDLE hConsoleOut;
CRITICAL_SECTION ScreenCritica;
char szSearchFor[1024];
int main(int argc, char *argv[])
{
WIN32_FIND_DATA *lpFindData;
HANDLE hFindFile;
HANDLE hThread;
DWORD dummy;
int i;
hConsoleOut = GetSetHandle(STD_OUTPUT_HANDLE);
if (argc != 2)
{
char errbuf[512];
wsprintf(errbuf, "Usage:%s<search-string>\n", argv[0]);
WriteFile(hConsoleOut, errbuf, strlen(errbuf), &dummy, FALSE);
return EXIT_FAILURE;
}
/*Put search string where everyone can see it */
strcpy(szSearchFor, argv[1]);
/* Allocate a find buffer to be handed to the first thread*/
lpFindData = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(WIN32_FIND_DATA));
/*Semaphore prevents too many threads from running*/
MTVERIFY(hThreadLimitSemaphore = CreateSemaphore(NULL, MAX_THREADS, MAX_THREADS, NULL));
InitializeCriticalSection(&ScreenCritical);
hFindFile = FindFirstFile("*.c", lpFindData);
if (hFindFile == INVALID_HANDLE_VALUE)
return EXIT_FAILURE;
do{
WaitForSingleObject(hThreadLimitSemaphore, INFINITE);
MTVERIFY(hThread = CreateThread(NULL, 0, SearchProc, lpFindData, 0, &dummy));
MTVERIFY(CloseHandle(hThread));
lpFindData = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
sizeof(WIN32_FIND_DATA));
} while (FindNextFile(hFindFile, lpFindData));
FindClose(hFindFile);
hFindFile = INVALID_HANDLE_VALUE;
for (i = 0; i < MAX_THREADS; i++)
WaitForSingleObject(hThreadLimitSemaphore, INFINITE); 
MTVERIFY(CloseHandle(hThreadLimitSemaphore));
return EXIT_SUCCESS;
}
DWORD WINAPI SearchProc(void *arg)
{
WIN32_FIND_DATA *lpFindData = (WIN32_FIND_DATA*)arg;
char buf[1024];
HANDLE hFile;
DWORD dummy;
hFile = CreateFile(lpFindData->cFileName, GENERIC_READ,
FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
if (!hFile)
return 1;
while (GetLine(hFile, buf, sizeof(buf)))
{
if (strstr(buf, szSearchFor))
{
EnterCriticalSection(&ScreenCritical);
WriteFile(hConsoleOut, strlen(lpFindData->cFileName), &dummy, FALSE);
WriteFile(hConsoleOut, ":", 2, &dummy, FALSE);
WriteFile(hConsoleOut, buf, strlen(buf), &dummy, FALSE);
WriteFile(hConsoleOut, "\r\n", 2, &dummy, FALSE);
LeaveCriticalSection(&ScreenCritical);
}
}
CloseHandle(hFile); 
HeapFree(GetProcessHeap(), 0, lpFindData);
MTVERIFY(ReleaseSemaphore(hThreadLimitSemaphore, 1, NULL));
}


BOOL GetLine(HANDLE hFile, LPSTR buf, DWORD size)
{
DWORD total = 0;
DWORD numread;
int state = 0;//0 = looking for non-newline 
              // 1 = stop after first newline
for (;;)
{
if (total == size - 1)
{
buf[size - 1] = '\0';
return TRUE;
}
if (!ReadFile(hFile, buf + total, 1, &numread, 0) ||
numread == 0)
{
buf[total] = '\0';
return total != 0;
}
if (buf[total] == 'r' || buf[total] == '\n')
{
if (state == 0)
continue;
buf[total] = '\0';
return TRUE;
}
state = 1;
total++;
}
}

仿多线程的效果一般有2种办法:第一种是通过定时器;第二种是启动多线程,不同模式下启动函数不同,mfc与API与WIN32下面注意点也是有区别的! VC启动一个新线程的三种方法,有需要的朋友可以参考下。 第一种AfxBeginThread() 用AfxBeginThread()函数来创建一个新线程来执行任务,工作者线程的AfxBeginThread的原型如下: CWinThread* AfxBeginThread(AFX_THREADPROC pfnThreadProc,   LPVOID lParam,   int nPriority = THREAD_PRIORITY_NORMAL,   UINT nStackSize = 0,   DWORD dwCreateFlags = 0,   LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL   );//用于创建工作者线程 返回值: 成功时返回一个指向新线程的线程对象的指针,否则NULL。 pfnThreadProc : 线程的入口函数,声明一定要如下: UINT MyThreadFunction(LPVOID pParam),不能设置为NULL; pParam : 传递入线程的参数,注意它的类型为:LPVOID,所以我们可以传递一个结构体入线程. nPriority : 线程的优先级,一般设置为 0 .让它和主线程具有共同的优先级. nStackSize : 指定新创建的线程的栈的大小.如果为 0,新创建的线程具有和主线程一样的大小的栈 dwCreateFlags : 指定创建线程以后,线程有怎么样的标志.可以指定两个值: CREATE_SUSPENDED : 线程创建以后,会处于挂起状态,直到调用:ResumeThread 0 : 创建线程后就开始运行. lpSecurityAttrs : 指向一个 SECURITY_ATTRIBUTES 的结构体,用它来标志新创建线程的安全性.如果为 NULL, 那么新创建的线程就具有和主线程一样的安全性. 如果要在线程内结束线程,可以在线程内调用 AfxEndThread. 一般直接用AfxBeginThread(ThreadProc,this); 示例: UINT myproc(LPVOID lParam){CITTDlg *pWnd = (CITTDlg *)lParam; //将窗口指针赋给无类型指针pWnd->KMeansSegment(); //要执行的函数return 1;}void CITTDlg::KMeansSegment(){// 主要处理函数在这里写}void CITTDlg::OnKMeansSegment() //按钮点击执行{AfxBeginThread(myproc, (LPVOID)this);//启动新的线程} 注意,工作者线程的函数必须是全局函数或静态成员函数,不能是普通的成员函数。 第二种CreateThread()函数原型为:HANDLECreateThread( NULL, // 没有安全描述符 0, // 默认线程栈的大小 MyThreadProc, // 线程函数指针,即函数名 (LPVOID)&n, // 传递参数 NULL, // 没有附加属性 NULL // 不需要获得线程号码 ); CreatThread,它返回的是一个句柄;如果不需要再监视线程,则用CloseHandle()关闭线程句柄。 线程的函数必须定义为: DWORD WINAPI MyThreadProc(LPVOID pParameter); 下面演示多线程操作控件,点击一个Button然后运行一个线程,将字符串显示在CEdit控件里面; 示例: .h头文件struct hS {CString Tmp;CTestDlg *hWnd; };//定义全局结构体,用来传递自定义消息DWORD WINAPI ThreadProc(LPVOIDlpParam);//线程函数声明,全局函数public: CString chtmp; struct hS *hTmp;protected: HANDLE m_hThread;//线程句柄 CEdit m_Edit;.cpp实现文件//线程执行函数DWORD WINAPI ThreadProc(LPVOID lpParam){//在这里写处理函数struct hS *Tmp2;Tmp2 = (hS*)lpParam;// 操作: Tmp2->hWnd->m_Edit.SetWindowText( (LPTSTR)Tmp2->Tmp );}void CTestDlg::OnBnClickedButton1(){ hTmp->Tmp = chtmp; hTmp->hWnd = this;//关键是把this指针传进去 m_hThread =CreateThread(NULL,0,ThreadProc,hTmp,0,NULL);//创建新线程 CloseHandle(m_hThread );} 用CreateThread()函数创建线程将返回一个线程句柄,通过该句柄你可以控制和操作该线程,当你不用时可以一创建该线程后就关闭该句柄,有专门的函CloseHandle()。关闭句柄不代表关闭线程,只是你不能在外部控制该线程(比如,提前结束,更改优先级等)。在线程结束后,系统将自动清理线程资源,但并不自动关闭该句柄,所以线程结束后要记得关闭该句柄。 第三种_beginthread() 函数原型为:intptr_t _beginthread( void( *start_address )( void * ), //指向新线程调用的函数的起始地址 unsigned stack_size, //堆栈大小,设置0为系统默认值 void *arglist //传递给线程函数的参数,没有则为NULL ); 返回值: 假如成功,函数将会返回一个新线程的句柄,用户可以像这样声明一个句柄变量存储返回值:   HANDLE hStdOut = _beginthread( CheckKey, 0, NULL )。如果失败_beginthread将返回-1。所在库文件: #include 线程函数的定义: 对于_beginthread()创建的线程,其线程函数定义为: void ThreadPro(void * pArguments ); _beginthreadex()为_beginthread()的升级版。 总结:AfxBeginThread是MFC的全局函数,是对CreateThread的封装。 CreateThread是Win32 API函数,AfxBeginThread最终要调到CreateThread。而_beginthread是C的运行库函数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值