前言 大家好吖,欢迎来到 YY 滴Linux系列 ,热烈欢迎! 本章主要内容面向接触过C++的老铁 主要内容含:

include <pthread.h>-lpthread”选项gcc test.c -o test.o -lpthread
功能:创建一个新的线程
原型
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg);
参数
thread:返回线程ID
attr:设置线程的属性,attr为NULL表示使用默认属性
start_routine:是个函数地址,线程启动后要执行的函数
arg:传给线程启动函数的参数
返回值:
成功返回0;失败返回错误码#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
void *rout(void *arg) {
int i;
for( ; ; ) {
printf("I'am thread 1\n");
sleep(1);
}
}
int main( void )
{
pthread_t tid;
int ret;
if ( (ret=pthread_create(&tid, NULL, rout, NULL)) != 0 ) {
fprintf(stderr, "pthread_create : %s\n", strerror(ret));
exit(EXIT_FAILURE);
}
int i;
for(; ; ) {
printf("I'am main thread\n");
sleep(1);
}
}pthread_exit
功能:线程终止
原型
void pthread_exit(void *value_ptr);
参数
value_ptr:value_ptr不要指向一个局部变量。
返回值:
无返回值,跟进程一样,线程结束的时候无法返回到它的调用者(自身)
pthread_cancel
功能:取消一个执行中的线程
原型
int pthread_cancel(pthread_t thread);
参数
thread:线程ID
返回值:
成功返回0;失败返回错误码// 线程函数
void* thread_function(void* arg) {
int num_seconds = *((int*)arg);
printf("Thread is running. Will sleep for %d seconds.\n", num_seconds);
sleep(num_seconds); // 休眠一段时间以模拟工作
printf("Thread has finished execution.\n");
pthread_exit(NULL); // 退出线程
}
int main() {
pthread_t thread;
int num_seconds = 5;
int* arg = &num_seconds;
// 创建线程
if (pthread_create(&thread, NULL, thread_function, (void*)arg) != 0) {
perror("Failed to create thread");
exit(EXIT_FAILURE);
}
// 等待线程完成
if (pthread_join(thread, NULL) != 0) {
perror("Failed to join thread");
exit(EXIT_FAILURE);
}
printf("Main thread has finished.\n");
return 0;
}功能:等待线程结束
原型
int pthread_join(pthread_t thread, void **value_ptr);
参数
thread:线程ID
value_ptr:它指向一个指针,后者指向线程的返回值(没有返回值就填NULL)
返回值:
成功返回0;失败返回错误码#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
void *thread1( void *arg )
{
printf("thread 1 returning ... \n");
int *p = (int*)malloc(sizeof(int));
*p = 1;
return (void*)p;
}
int main( void )
{
pthread_t tid;
void *ret;
pthread_create(&tid, NULL, thread1, NULL);
pthread_join(tid, &ret);
// pthread_join(tid, NULL);没有返回值就填NULL
printf("thread return, thread id %X, return code:%d\n", tid, *(int*)ret);
free(ret);
return 0;
}注意:
-- 线程组内其他线程对目标线程进行分离
int pthread_detach(pthread_t thread);
-- 线程内自己分离
pthread_detach(pthread_self());#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
void *thread_run( void * arg )
{
pthread_detach(pthread_self());//线程内自己分离,进入分离状态
printf("%s\n", (char*)arg);
return NULL;
}
int main( void )
{
pthread_t tid;
if ( pthread_create(&tid, NULL, thread_run, "thread1 run...") != 0 ) {
printf("create thread error\n");
return 1;
}
//不需要调用 pthread_join
int ret = 0;
return ret;
}