cpp在Windows和Linux系统创建线程的方法

⌚Time: 2022-05-27 21:00:05

👨‍💻Author: Jack Ge

windows创建线程

windows系统下使用CreateThread函数创建线程,使用WaitForSingleObject函数等待线程退出

CreateThread函数原型


HANDLE CreateThread(

LPSECURITY_ATTRIBUTES lpThreadAttributes,//SD

SIZE_T dwStackSize,//initialstacksize

LPTHREAD_START_ROUTINE lpStartAddress,//threadfunction

LPVOID lpParameter,//threadargument

DWORD dwCreationFlags,//creationoption

LPDWORD lpThreadId//threadidentifier

)

WaitForSingleObject函数原型


DWORD WaitForSingleObject(

HANDLE hHandle,

DWORD dwMilliseconds

);

线程函数格式


DWORD WINAPI 函数名 (LPVOID lpParam); //标准格式

DWORD WINAPI 函数名 (LPVOID lpParam)

{

    return 0;

}

CreateThread(NULL, 0, 函数名, 0, 0, 0);

void 函数名();

使用void 函数名()此种线程声明方式时,lpStartAddress需要加入LPTHREAD_START_ROUTINE转换,如

void 函数名()

{

    return;

}

CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)函数名, 0, 0, 0);

例子:

mythread_windows.cpp


#include<windows.h>

#include<iostream>

using namespace std;



DWORD WINAPI function(LPVOID lpParam){

    Sleep(1000);

    for(int i=0;i<3;i++){

        cout<<"thread "<<*(char*)lpParam<<" running"<<endl;

        Sleep(1000);

    }

}

int main(){

    DWORD threadID;

    HANDLE hThread[3];

    hThread[0]=CreateThread(NULL,0,function,(LPVOID)"a",0,&threadID);

    cout<<"thread "<<threadID<<" created"<<endl;

    hThread[1]=CreateThread(NULL,0,function,(LPVOID)"b",0,&threadID);

    cout<<"thread "<<threadID<<" created"<<endl;

    hThread[2]=CreateThread(NULL,0,function,(LPVOID)"c",0,&threadID);

    cout<<"thread "<<threadID<<" created"<<endl;

    WaitForSingleObject(hThread[0],INFINITE);

    WaitForSingleObject(hThread[1],INFINITE);

    WaitForSingleObject(hThread[2],INFINITE);

    return 0;

}

编译运行


linux创建线程

linux系统下使用pthread_create函数创建线程并使用pthread_join函数等待线程退出

pthread_create函数原型


int pthread_create(

pthread_t *tidp,

const pthread_attr_t *attr,

void *(*start_rtn)(void*),

void *arg

);

第一个参数为指向线程标识符的指针。

第二个参数用来设置线程属性。

第三个参数是线程运行函数的起始地址。

最后一个参数是运行函数的参数。

pthread_join函数原型


int pthread_join(

pthread_t thread, 

void **retval

);

线程函数格式


void* 函数名(void* param){



}

链接时用到的库:pthread

例子:

mythread_linux.c


#include<stdio.h>

#include<pthread.h>

void* function(void* param){

    int i;

    sleep(1);

    for(i=0;i<3;i++){

        printf("thread %s is running\n",(char*)param); 

        sleep(1);

    }

}

int main(){



    pthread_t threadID[3];

    if(0 == pthread_create(&threadID[0],NULL,function,(void*)"a")){

        printf("thread %d created\n",threadID[0]);

    }

    if(0 == pthread_create(&threadID[1],NULL,function,(void*)"b")){

        printf("thread %d created\n",threadID[1]);

    }

    if(0 == pthread_create(&threadID[2],NULL,function,(void*)"c")){

        printf("thread %d created\n",threadID[2]);

    }

    pthread_join(threadID[0],NULL);

    pthread_join(threadID[1],NULL);

    pthread_join(threadID[2],NULL);

    return 0;

}


编译运行


gcc mythread_linux.c -lpthread

./a.out