阅读量:2
在 Linux 中,使用 C 语言创建线程可以通过以下两种方法实现:
- 使用 POSIX 线程库(pthread)
首先,需要包含头文件 pthread.h。然后,通过调用 pthread_create() 函数来创建线程。这是一个简单的示例:
#include
#include
#include
void *my_thread_function(void *arg) {
printf("Hello from the new thread!\n");
pthread_exit(NULL);
}
int main() {
pthread_t thread_id;
int rc;
rc = pthread_create(&thread_id, NULL, my_thread_function, NULL);
if (rc != 0) {
perror("Failed to create thread");
exit(EXIT_FAILURE);
}
printf("Hello from the main thread!\n");
// 等待线程结束
pthread_join(thread_id, NULL);
return 0;
}
- 使用系统调用
clone()
clone() 系统调用是 Linux 中创建线程的另一种方法。首先,需要包含头文件 sys/types.h 和 sys/wait.h。然后,通过调用 clone() 函数来创建线程。这是一个简单的示例:
#include
#include
#include
#include
#include
int my_thread_function(void *arg) {
printf("Hello from the new thread!\n");
_exit(0);
}
int main() {
pid_t pid = clone(my_thread_function, NULL, CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_THREAD | CLONE_SYSVSEM, NULL);
if (pid < 0) {
perror("Failed to create thread");
exit(EXIT_FAILURE);
}
printf("Hello from the main thread!\n");
// 等待线程结束
waitpid(pid, NULL, 0);
return 0;
}
这两种方法都可以用于在 Linux 中使用 C 语言创建线程。POSIX 线程库(pthread)是现代 Linux 系统中更常用的方法,因为它提供了更丰富的功能和更好的可移植性。
以上就是关于“linux c语言如何创建线程”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm