linux线程笔记1之创建线程

1 线程与进程的对比

  这里有一个笔记详细的阐述

  http://blog.csdn.net/laviolette/article/details/51506953

2 创建线程函数

  int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);

  参数意义:

    typedef unsigned long int pthread_t

    (1)pthread_t *thread:存储线程ID 唯一

    (2)const pthread_attr_t *attr:线程属性 设置与栈相关的属性 通常为NULL

    (3)void *(*start_routine) (void *):函数指针 指定运行哪个函数代码

    (4)void *arg:运行函数的参数地址 通常给自定义函数传入参数

例子:创建新线程 并使用结构体传递多个参数 注意编译的时候就加上-lpthread

 1 #include <pthread.h>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <string.h>
 5 
 6 struct student
 7 {
 8     int age;
 9     char* name;
10 };
11 
12 void *print(struct student *str)
13 {
14     printf("the age is %d
",str->age);
15     printf("the name is %s
",str->name);
16 }
17 
18 int main()
19 {
20     struct student stu;
21     pthread_t thread_id;
22     stu.age = 18;
23     stu.name = "gogogo";
24     pthread_create(&thread_id,NULL,(void*)*print,&stu);//创建线程
25     printf("the new thread id is %u
",thread_id);
26     pthread_join(thread_id,NULL);//在主线程等待子线程结束
27     return 1;
28 }

补充:int pthread_join(pthread_t thread, void **retval);线程等待函数

    

原文地址:https://www.cnblogs.com/lanjianhappy/p/6885192.html