操作系统(5) (POSIX--Linux线程编程pthread_t/create/join/exit)
目录
1.pthread_create()
2. pthread_join
3. pthread_exit()
4.pthread_t
5. 代码应用
解释:
1.pthread_create()
- 作用:用于创建一个新的线程。
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);
pthread_t *thread
:存储线程的 ID。const pthread_attr_t *attr
:线程的属性。如果设置为NULL
,则使用默认属性。void *(*start_routine)(void *)
:线程将要执行的函数。void *arg
:传递给线程函数的参数。
2. pthread_join
作用:等待指定的线程完成执行,类似于进程中的 wait()
,主线程会等待指定的子线程运行完毕再继续执行。
int pthread_join(pthread_t thread, void **retval);
pthread_t thread
:需要等待的线程 ID。void **retval
:用于获取线程的返回值。如果不需要获取,可以传NULL
。
3. pthread_exit()
作用:用于终止调用它的线程,可以提供一个返回值供其他线程通过 pthread_join()
获取。
void pthread_exit(void *retval);
void *retval
:线程的返回值,供pthread_join()
获取。
4.pthread_t
- 作用:这是一个数据类型,用于存储线程的 ID。类似于进程中的
pid_t
,用于标识和管理不同的线程。
pthread_t thread_id;
pthread_create(&thread_id, NULL, &thread_function, (void *) &argument);
pthread_join(thread_id, NULL);
- pthread_t thread_id;
- pthread_create(&thread_id, NULL, &thread_function, (void *) &argument);
- pthread_join(thread_id, NULL);
pthread_create()
用于创建线程。pthread_join()
用于等待线程结束。pthread_exit()
用于线程退出。pthread_t
是线程的标识符类型,用于存储线程 ID。
5. 代码应用
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
// 线程函数,接收一个参数并打印该参数的值
void* print_message_function(void* arg) {
char* message = (char*) arg;
printf("%s\n", message);
pthread_exit(NULL); // 线程退出
}
int main() {
pthread_t thread1, thread2; // 定义两个线程 ID
const char* message1 = "Thread 1: Hello, World!";
const char* message2 = "Thread 2: Welcome to threading!";
// 创建第一个线程,执行 print_message_function,传递 message1
if (pthread_create(&thread1, NULL, print_message_function, (void*) message1) != 0) {
printf("Error: Unable to create thread 1\n");
exit(1);
}
// 创建第二个线程,执行 print_message_function,传递 message2
if (pthread_create(&thread2, NULL, print_message_function, (void*) message2) != 0) {
printf("Error: Unable to create thread 2\n");
exit(1);
}
// 使用 pthread_join() 等待两个线程完成
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
// 主线程执行完毕
printf("All threads completed.\n");
return 0;
}
解释:
-
创建线程:
pthread_create(&thread1, NULL, print_message_function, (void*) message1);
:- 这是创建线程的函数。
thread1
是线程的 ID。NULL
代表默认线程属性。print_message_function
是线程执行的函数。(void*) message1
是传递给线程函数的参数。
-
线程函数
print_message_function
:- 线程函数接受一个
void*
类型的参数。在这里我们将其转换为char*
,并打印它。 pthread_exit(NULL);
用于退出线程。
- 线程函数接受一个
-
等待线程完成:
pthread_join(thread1, NULL);
和pthread_join(thread2, NULL);
用于等待线程thread1
和thread2
完成。NULL
表示不获取线程的返回值。
-
输出:
程序将输出两个线程的消息,依次打印出:
Thread 1: Hello, World!
Thread 2: Welcome to threading!
然后,主线程会等待两个线程结束,最后打印 All threads completed.
。
编译和运行:与线程有关的要使用-pthread编译
gcc -o thread_example thread_example.c -pthread
./thread_example