linux线程系列(3)线程创建

来源:互联网 发布:网络没问题游戏上不去 编辑:程序博客网 时间:2024/05/29 10:40
    线程创建函数如下:

#include <pthread.h>

int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void*), void *restrict arg);

返回: 成功返回0,否则返回错误编号

参数

tidp:线程标识符指针

attr:线程属性指针

start_rtn:线程运行函数的起始地址

arg:传递给线程运行函数的参数

注意:新创建线程从start_rtn函数的地址开始运行,但不能保证新线程和调用线程的执行顺序。

实例代码:创建两个子线程

#include <pthread.h>#include <stdio.h>#include <stdlib.h>#include <math.h>#include <unistd.h>typedef struct{    char name[20];    int time;    int start;    int end;}RaceArg;void* th_fn(void *arg){    RaceArg *r = (RaceArg *)arg;    int i = r->start;        for(; i <= r->end; i++)    {        printf("%s(%lx) run %d\n", r->name, pthread_self(), i);        usleep(r->time);//微秒    }    return (void*)0;}int main(){    int err;    pthread_t rabbit, turtle;    RaceArg r_a = {"rabbit", (int)(drand48()*100000), 20, 50};    RaceArg t_a = {"turtle", (int)(drand48()*100000), 20, 50};    if((err = pthread_create(&rabbit, NULL, th_fn, (void*)&r_a)) != 0)    {        perror("pthread create error");    }    if((err = pthread_create(&turtle, NULL, th_fn, (void*)&t_a)) != 0)    {        perror("pthread create error");    }    pthread_join(rabbit, NULL);    pthread_join(turtle, NULL);    printf("control thread id: %lx\n", pthread_self());    printf("finished!\n");    return 0;}


    对于以上的代码内存空间分配图如下(假设g_v是一个全局变量):

                          

    主线程启动的两个子线程拥有自己的栈空间,子线程各种栈空间中的局部变量是子线程私有的,外部不可访问(子线程的局部变量i,r都存储在私有的栈中)。对于数据段和堆中的数据是主线程和两个子线程共享的,因此为了安全起见,子线程尽量使用局部变量,保证线程的变量不被其它线程修改。(子线程如果申请内存空间,会分配到堆空间,堆空间是共享的,这点需要注意)


原创粉丝点击