windows下使用pthread

有的时候需要使用多线程来测试代码啥的,在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
");
        fflush(stdout);
        Sleep(1000);
    }

    return NULL;
}

void *thread2(void *arg)
{
    while (1)
    {
        printf("T2T2T2T2T2
");
        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.
");

    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.
");
    return EXIT_SUCCESS;
}

需要着重说明的函数是pthread_join,功能是等待Tid2线程返回才会继续向下跑。

执行结果:

报错误1:e:mingwincludepthread.h:320:8: error: redefinition of 'struct timespec'

那么在GCC C Compiler -> Symbols中添加HAVE_STRUCT_TIMESPEC定义。

如上面的方法不行,那么使用mingw-install-setup.exe添加安装pthread相关的库:

原文地址:https://www.cnblogs.com/tfanalysis/p/5505163.html