C++ Thread API的学习之一

Thread API函数使用:
thread_create(), thread_join(), thread_exit().
代码实例中涉及到线程的创建,传参和返回值,返回值的接受。
参考:《POSIX多线程程序设计中文版》中2.1 建立和使用线程 。

实例代码:

//thread_create(), thread_join(), thread_exit()
#include <pthread.h>  
#include <stdio.h>
//#include <iostream>
//using namespace std;

void* thread_one(void* arg)
{
    int *iarg = (int*)arg;
    //cout << "thread_two " << *iarg << endl;
    printf("thread_one %d\n", *iarg);
    *iarg = 129;
    pthread_exit((void*)arg);
}

void* thread_two(void* arg)
{
    int *iarg = (int*)arg;
    //cout << "thread_two " << *iarg << endl;
    printf("thread_two %d\n", *iarg);
    *iarg = 130;
    return arg;
}


int main(int argc, char* argv[])
{
    pthread_t pid_one = 0;
    pthread_t pid_two = 0;
    int ione = 128;
    int itwo = 128;
    int *pone = &ione;
    int *ptwo = &itwo;
    int ret = pthread_create(&pid_one, NULL, thread_one, (void*)pone);
    if(0 != ret){
        //cout << "pthread one create error!" << endl;
        printf("pthread one create error!\n");
        return 0;
    }
    ret = pthread_create(&pid_two, NULL, thread_two, (void*)ptwo);
    if(0 != ret){
        //cout << "pthread two create error!" << endl;
        printf("pthread two create error!\n");
        return 0;
    }
    pthread_join(pid_one, (void**)(&pone));
    pthread_join(pid_two, (void**)(&ptwo));
    //cout << "Thread one " << ione << endl;
    //cout << "Thread two " << itwo << endl;
    printf("Thread one return %d\n", ione);
    printf("Thread two return %d\n", itwo);
    return 0;
}

输出结果:

$ ./test
thread_one 128
thread_two 128
Thread one return 129
Thread two return 130

代码实例中如果使用cout会出现多线程输出混乱:

$ ./test
thread_one thread_two 128128

Thread one 129
Thread two 130
$ ./test
thread_one thread_two 128
128
Thread one 129
Thread two 130
$ ./test
thread_one thread_two 128128

Thread one 129
Thread two 130

猜你喜欢

转载自blog.csdn.net/feng973/article/details/79391115