极光城

创建一个POSIX线程[C++]

POSIX表示可移植操作系统接口(Portable Operating System Interface of UNIX,缩写为 POSIX ),是IEEE为要在各种UNIX操作系统上运行的软件而定义的一系列API标准的总称,其正式称呼为IEEE 1003,而国际标准名称为ISO/IEC 9945。

简而言之,POSIX标准是一个很大的函数列表,包括很多API的名字,也就是函数名,同时也规定了函数调用时参数入栈的顺序与返回值存储的寄存器等等。如果某个操作系统能实现这个函数列表的所有函数,可以认为就是符合POSIX标准的。 虽然事实上POSIX规定的技术细节还要多很多,但是大体原则不变。

POSIX 线程的头文件是 POSIX Thread ———— pthread.h 这是我们写代码是需要包含的主要头文件。

首先我们定义一个函数,用以作为线程函数使用:

util.h

void* function(void*);

实现这个函数

util.cpp

#include <iostream>
using namespace std;
 
void* function(void* p)
{
    int flag=0;
    if(p)
        flag = *((int *)p);
    for(int i=0;i<10;i++)
    {
        cout<<"func"<<flag<<" "<<i<<endl;
    }
    int * result = new int;
    *result = (*(int *)p) + 2;
    return (void*) result;
}

之后写一个主程序,利用这个函数开启两个线程

main.cpp

#include <iostream>
#include <pthread.h>
#include "util.h"
 
using namespace std;
 
/*
typedef unsigned long int pthread_t;
extern int pthread_create __P ((pthread_t *__thread, __const pthread_attr_t *__attr,
void *(*__start_routine) (void *), void *__arg));
*/
int main()
{
    pthread_t t1,t2;
 
    int i1=1,i2=2;
    pthread_create(&t1,NULL,function,&i1);
    pthread_create(&t2,NULL,function,&i2);
    for(int i=0;i<10;i++)
    {
        cout<<"main"<<i<<endl;
    }
    void * result1,* result2;
    pthread_join(t1,&result1);
    pthread_join(t2,&result2);
 
    cout<<"thread joined with result:"<<endl;
    cout<<*(int *)result1<<" "<<*(int *)result2<<endl;
 
    delete (int *)result1;delete (int *)result2;
 
    return 0;
}

编译

gcc main.cpp -lpthread