有的時候需要使用多線程來測試代碼啥的,在Linux下有pthread,在windows也有。
我這兒是使用MingW作為編譯工具,具體如何下載MingW自行在網上搜索。
而pthread是在這里下載的:ftp://sourceware.org/pub/pthreads-win32/pthreads-w32-2-9-1-release.zip
將下載來的包解壓,然后將Pre-built.2中的include下的文件拷貝到mingw/include中,將lib/x86(或x64)/libpthreadGC2.a拷貝到mingw/lib中。
之后使用的時候,在Eclipse的Linker選項里添加一個新的庫pthreadGC2即可了。
下面是源代碼:
/* ============================================================================ Name : t3.c Author : Merlin Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <windows.h> void *thread1(void *arg) { while (1) { printf("T1T1T1T1T1T1T1T1T1T1T1\n"); fflush(stdout); Sleep(1000); } return NULL; } void *thread2(void *arg) { while (1) { printf("T2T2T2T2T2\n"); fflush(stdout); Sleep(2000); } return NULL; } int main(void) { void *Tret; pthread_t Tid1, Tid2; // HWND Wnd; // Wnd = FindWindow(NULL, "微信"); // if (Wnd) // { //// SendMessage(Wnd, WM_CLOSE, 0, 0); // ShowWindow(Wnd, SW_HIDE); // Sleep(2000); // ShowWindow(Wnd, SW_SHOW); // Sleep(2000); // ShowWindow(Wnd, SW_HIDE); // } printf("Hello, this is a example test pthread.\n"); pthread_create(&Tid1, NULL, thread1, NULL); pthread_create(&Tid2, NULL, thread2, NULL); pthread_join(Tid2, &Tret); Sleep(100); printf("End, this is a example test pthread.\n"); return EXIT_SUCCESS; }
需要着重說明的函數是pthread_join,功能是等待Tid2線程返回才會繼續向下跑。
執行結果:
報錯誤1:e:\mingw\include\pthread.h:320:8: error: redefinition of 'struct timespec'
那么在GCC C Compiler -> Symbols中添加HAVE_STRUCT_TIMESPEC定義。
如上面的方法不行,那么使用mingw-install-setup.exe添加安裝pthread相關的庫: