温馨提示×

Linux多线程怎么创建

小亿
104
2023-08-16 10:20:42
栏目: 智能运维

在Linux中,可以使用pthread库来创建多线程。下面是一个简单的例子:

#include <stdio.h>
#include <pthread.h>
// 线程函数
void *thread_func(void *arg) {
int thread_num = *((int*)arg);
printf("Hello from thread %d\n", thread_num);
pthread_exit(NULL);
}
int main() {
pthread_t thread1, thread2; // 两个线程
int thread1_num = 1;
int thread2_num = 2;
// 创建线程1
pthread_create(&thread1, NULL, thread_func, (void*)&thread1_num);
// 创建线程2
pthread_create(&thread2, NULL, thread_func, (void*)&thread2_num);
// 等待线程1结束
pthread_join(thread1, NULL);
// 等待线程2结束
pthread_join(thread2, NULL);
return 0;
}

在这个例子中,我们创建了两个线程,每个线程都会调用thread_func函数。pthread_create函数用于创建线程,它接受四个参数:线程的标识符、线程的属性、线程函数、传递给线程函数的参数。pthread_join函数用于等待线程结束。

编译并运行这个程序后,你应该可以看到类似以下的输出:

Hello from thread 1
Hello from thread 2

0