linux中如何创建一个线程
时间: 2024-05-03 07:21:14 浏览: 14
在Linux中创建线程有两种方式:
1. pthread_create()函数
pthread_create()函数是POSIX标准线程库中创建线程的函数,其函数原型如下:
```c
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
```
参数说明:
- thread:指向线程标识符的指针
- attr:线程属性
- start_routine:线程函数的指针
- arg:传递给线程函数的参数
示例代码:
```c
#include <stdio.h>
#include <pthread.h>
void *thread_func(void *arg)
{
printf("Hello, I am a new thread!\n");
return NULL;
}
int main()
{
pthread_t tid;
int ret;
ret = pthread_create(&tid, NULL, thread_func, NULL);
if (ret != 0) {
printf("Failed to create thread!\n");
return -1;
}
printf("Main thread: Created a new thread (thread ID: %ld)\n", tid);
pthread_exit(NULL);
return 0;
}
```
2. clone()系统调用
clone()系统调用可以创建一个线程,其函数原型如下:
```c
int clone(int (*fn)(void *), void *child_stack, int flags, void *arg, .../* pid_t *ptid, void *tls, pid_t *ctid */);
```
参数说明:
- fn:线程函数指针
- child_stack:子线程的栈空间
- flags:线程创建标志
- arg:传递给线程函数的参数
示例代码:
```c
#define _GNU_SOURCE
#include <stdio.h>
#include <sched.h>
void *thread_func(void *arg)
{
printf("Hello, I am a new thread!\n");
return NULL;
}
int main()
{
char *stack;
char *stack_top;
int ret;
stack = malloc(1024*1024);
stack_top = stack + 1024*1024;
ret = clone(thread_func, stack_top, CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_VM, NULL);
if (ret == -1) {
printf("Failed to create thread!\n");
return -1;
}
printf("Main thread: Created a new thread (thread ID: %ld)\n", ret);
return 0;
}
```
注意:clone()系统调用需要在程序中定义宏#define _GNU_SOURCE才能使用。