Linux系统编程——多线程编程(一)
Linux系统编程——多线程编程(一)
pthread_create函数
int pthread_create(pthread_t *thread, const pthread_attr_t* attr,void* (*start_routine)(void*), void* arg);
功能:创建一个线程运行start_routine执行的函数。
thread:线程信息
attr:线程属性,一般设置为NULL
start_routine:所要运行的函数
arg:运行函数的参数
返回值:成功返回0,失败返回错误码
pthread_join函数
int pthread_join(pthread_t thread, void** retval);
功能:等待thread对应的线程结束。
thread:线程信息。
retval:线程返回值,为NULL时忽略。
返回值:成功返回0,失败返回错误码。
pthread_exit函数
int pthread_exit(void* retvall);
功能:退出线程,类似于退出进程的exit函数
retval:退出状态码。
返回值:总是成功,因此忽略。
pthread_cancel函数
int pthread_cancel(pthread_t thread)
功能:向线程thread发送一个取消请求。目标线程是否以及何时对该取消请求作出响应,取决于该线程控制的两个属性。
返回值:成功返回0,失败返回错误码。
实例:多线程实现终端输入输出
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>char buf[256];
int flag = 0;
void* thread_func(void* arg)
{while (1){if(flag) {puts(buf);if (strncmp(buf, "quit",4) == 0) {pthread_exit(NULL);}flag = 0;}}return 0;}int main()
{pthread_t tid;if (pthread_create(&tid, NULL, thread_func, NULL) != 0) {perror("pthread_create failed");return 1;}while (1) {fgets(buf,sizeof(buf),stdin);if(strncmp(buf, "quit", 4) == 0) {break;}flag = 1;}pthread_join(tid, NULL);return 0;
}
执行结果:

