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

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 2

int 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;
}

运行结果








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值