多线程

1.要点:

1.多线程编译时要用 “gcc thread.c -lpthread -o thread” 调用静态库编译。
2.线程要在sleep内运行,sleep结束就无法调用线程运行了。(usleep是微秒级的延时)
3.多线程宏观上可以看作是并发的(实际只是分时复用而已),因此不需要考虑sleep切换给其他线程,系统会自动分配时间片。
4.全局变量是共同拥有的。(与进程不同)
5.创建线程传参时最好用结构体

2.相关函数:

创建线程pthread_create

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

thread 线程标识符;
attr 线程属性设置;
start_routine 线程函数的起始地址;
arg 传递给start_routine的参数;
头文件 #include <pthread.h>
返回值 成功,返回0;出错,返回-1。
说明: 创建一个具有指定参数的线程。
示例: pthread_t thread1; pthread_create(&thread1, NULL, (void *)(&fun), (void *)arg);

等待线程结束函数pthread_join

int pthread_join(pthread_t thread, void **retval)

thread 线程标识符;
retval 一个用户定义的指针,获取该结束线程的返回参数
头文件 #include <pthread.h>
返回值 若是成功建立线程返回0,否则返回错误的编号
说明: 这个函数是一个线程阻塞的函数,调用它的函数将一直等待到被等待的线程结束为止,当函数返回时,被等待线程的资源被收回
示例: pthread_t thread1; pthread_join (&thread1, (void *) &retval);

线程终止函数pthread_exit

void pthread_exit(void* retval)

retval 一个用户定义的指针,它可以用来存储被等待线程的返回值
头文件 #include <pthread.h>
返回值 None
说明: 终止线程,并传递参数retval的地址。
示例: pthread_ exit (&retval);

获取当前线程标识ID pthread_self

pthread_t pthread_self(void);

头文件 #include <pthread.h>
返回值 当前线程的线程ID标识
说明: 获取当前调用线程的 thread identifier(标识号)
示例: pthread_t thread1; thread1 = pthread_self();
posted @ 2018-01-15 21:22  WittXie  阅读(227)  评论(0编辑  收藏  举报