使用pthreads基本函数编写helloworld.c

来源:互联网 发布:单片机学习 编辑:程序博客网 时间:2024/06/09 17:05

Linux下的多线程程序使用pthread库。

对应函数有:

创建线程:pthread_create(pthread_t*, thrad, pthread_attr_t * attr, void* (start_routine)(void*)), void* arg);

退出线程:主动退出:pthread_exit(void* val); 被动退出:pthread_cancel(pthread_t thread);

等待线程结束替其清理内存:pthread_join(pthread_t thread, void** thread_return);

让线程退出时自己清理其内存:int pthread_detach(pthread_t th);

获得当前线程的标志:pthread_t pthread_self(void);


编译命令:gcc helloworld.c -o helloworld -lpthread -std=c99

/*************************************************************************> File Name: helloworld.c> Author: > Mail: > Created Time: Tue 23 Aug 2016 09:45:08 PM CST ************************************************************************/#include <stdio.h>#include <stdlib.h>#include <pthread.h>#include <unistd.h>#define THREAD_NUMBER 2int retval_hello1 = 1;int retval_hello2 = 2;void* hello1(void* arg){    char* hello_str = (char *)arg;    sleep(1);    printf("%s\n", hello_str);    pthread_exit(&retval_hello1);}void* hello2(void* arg){    char* hello_str = (char *)arg;    sleep(2);    printf("%s\n", hello_str);    pthread_exit(&retval_hello2);}int main(){    int retval;    int *retval_hello[2];    pthread_t pt[2];    const char* arg[THREAD_NUMBER];    arg[0] = "hello world from thread1.";    arg[1] = "hello world from thread2.";    printf("begin to create threads....\n");    retval = pthread_create(&pt[0], NULL, hello1, (void*)arg[0]);    if(retval != 0){        printf("pthread_create error.");        exit(1);    }    retval = pthread_create(&pt[1], NULL, hello2, (void*)arg[1]);    if(retval != 0){        printf("pthread_create error.");        exit(1);    }    printf("now, the main thread returns.\n");    printf("main thread begin to wait threads.\n");    for(int i=0;i<THREAD_NUMBER;i++){        retval = pthread_join(pt[i], (void **)&retval_hello[i]);        if(retval != 0){            printf("pthread_join error");            exit(1);        }else{           // if(retval_hello[0] == &retval_hello1){           //     printf("the same");           // }            printf("return value is %d\n", *retval_hello[i]);        }    }    return 0;}

运行结果








0 0
原创粉丝点击