在Linux操作系统中,线程和进程是两个核心概念,它们之间的关系如下:
进程:
线程:
以下是一个简单的多线程示例代码,使用C语言和pthread库:
#include <stdio.h>
#include <pthread.h>
void* thread_func(void* arg) {
int id = *(int*)arg;
printf("Thread %d is running
", id);
return NULL;
}
int main() {
pthread_t threads[5];
int thread_ids[5];
for (int i = 0; i < 5; ++i) {
thread_ids[i] = i;
pthread_create(&threads[i], NULL, thread_func, &thread_ids[i]);
}
for (int i = 0; i < 5; ++i) {
pthread_join(threads[i], NULL);
}
printf("All threads are finished
");
return 0;
}
这个示例代码创建了5个线程,每个线程打印自己的ID。通过pthread_create
创建线程,通过pthread_join
等待线程结束。
希望这些信息对你有所帮助!
领取专属 10元无门槛券
手把手带您无忧上云