在Linux应用中创建多线程任务通常使用pthread库(POSIX Threads)。下面是一个简单的C语言示例,演示如何在Linux中创建多线程任务:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 5
// 线程函数
void *thread_func(void *thread_id) {
long tid;
tid = (long)thread_id;
printf("Hello World! It's me, thread #%ld!\n", tid);
pthread_exit(NULL);
}
int main() {
pthread_t threads[NUM_THREADS];
int rc;
long t;
// 创建多个线程
for(t = 0; t < NUM_THREADS; t++) {
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, thread_func, (void *)t);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
// 等待所有线程结束
for(t = 0; t < NUM_THREADS; t++) {
pthread_join(threads[t], NULL);
}
printf("All threads completed. Exiting.\n");
pthread_exit(NULL);
}
上述代码中,我们首先包含了必要的头文件<stdio.h>
, <stdlib.h>
, 和 <pthread.h>
。然后定义了宏NUM_THREADS
表示线程的数量。
接着定义了一个线程函数thread_func
,它接受一个void*
类型的参数,并在函数中将其转换为long
类型,然后打印出相应的线程号。该函数是由每个线程执行的实际任务。
在main
函数中,我们声明了一个pthread_t
类型的数组来存放线程的标识符,以及一些变量用于循环和错误检查。在循环中,我们使用pthread_create
函数创建了多个线程,并将其与指定的线程函数进行关联。然后,我们使用pthread_join
函数等待所有线程执行完毕。
最后,我们打印一条消息表示所有线程已经完成,并退出程序。
要编译这个程序,您可以使用如下命令:
gcc -o multithreading_example multithreading_example.c -lpthread
然后运行生成的可执行文件:
./multithreading_example
会看到输出类似于:
In main: creating thread 0
Hello World! It's me, thread #0!
In main: creating thread 1
Hello World! It's me, thread #1!
In main: creating thread 2
Hello World! It's me, thread #2!
In main: creating thread 3
Hello World! It's me, thread #3!
In main: creating thread 4
Hello World! It's me, thread #4!
All threads completed. Exiting.
这证明了多线程任务已经成功创建并执行