Linux下用C语言写一个创建线程的代码
时间: 2023-05-21 10:03:16 浏览: 54
可以使用pthread库来创建线程,以下是一个简单的示例代码:
```c
#include <stdio.h>
#include <pthread.h>
void *thread_func(void *arg)
{
printf("Hello, world!\n");
return NULL;
}
int main()
{
pthread_t thread;
int ret = pthread_create(&thread, NULL, thread_func, NULL);
if (ret != 0) {
printf("Failed to create thread!\n");
return 1;
}
pthread_join(thread, NULL);
return 0;
}
```
在这个示例中,我们定义了一个名为`thread_func`的函数作为线程的入口点,它会输出一条简单的消息。在`main`函数中,我们使用`pthread_create`函数创建一个新的线程,并将`thread_func`作为线程的入口点。`pthread_join`函数用于等待线程结束。
相关问题
linux下C语言如何创建一个线程
在Linux下,可以使用pthread库来创建线程。具体步骤如下:
1. 包含pthread头文件
```c
#include <pthread.h>
```
2. 定义线程函数
```c
void *thread_func(void *arg) {
// 线程处理的逻辑
}
```
3. 创建线程
```c
pthread_t thread_id;
pthread_create(&thread_id, NULL, thread_func, arg);
```
其中,第一个参数是线程ID,第二个参数是线程属性(可以为NULL),第三个参数是线程函数,第四个参数是传递给线程函数的参数。
4. 等待线程结束
```c
pthread_join(thread_id, &ret_val);
```
其中,第一个参数是线程ID,第二个参数是线程的返回值指针。如果不需要返回值,可以为NULL。
完整的示例代码如下:
```c
#include <stdio.h>
#include <pthread.h>
void *thread_func(void *arg) {
int *num_ptr = (int *)arg;
printf("Thread running with argument %d\n", *num_ptr);
pthread_exit(NULL);
}
int main() {
int num = 10;
pthread_t thread_id;
pthread_create(&thread_id, NULL, thread_func, &num);
pthread_join(thread_id, NULL);
return 0;
}
```
这个示例程序创建了一个线程,调用thread_func函数,并传递了一个int类型的参数。线程函数简单地打印了传递进来的参数,然后退出。主线程等待子线程结束,然后退出程序。
windows系统,c语言代码,写一个创建多个线程的代码
好的,以下是一个简单的 C 语言代码示例,可以创建多个线程:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 5 // 定义创建线程的数量
// 线程函数
void *thread_func(void *thread_id) {
long tid = (long)thread_id;
printf("Thread %ld is running\n", tid);
pthread_exit(NULL); // 线程退出
}
int main() {
pthread_t threads[NUM_THREADS]; // 存储线程ID的数组
int rc;
long t;
for (t = 0; t < NUM_THREADS; t++) {
printf("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);
}
}
pthread_exit(NULL); // 主线程退出
return 0;
}
```
以上代码中,首先定义了一个常量 `NUM_THREADS` 表示要创建的线程数量。然后定义了一个线程函数 `thread_func`,它会输出一个线程ID,然后退出线程。在 `main` 函数中,使用一个循环创建指定数量的线程,并将线程ID 存储在 `threads` 数组中。创建线程时,调用了 `pthread_create` 函数。该函数接受四个参数:线程ID、线程属性、线程函数、和线程函数的参数。最后,主线程调用了 `pthread_exit` 函数,等待所有线程退出后再退出整个进程。
注意:在 Windows 系统上,需要使用另外的线程库,如 Win32 API 或者 C++11 标准库的 `std::thread`。上述代码只适用于 Linux 或者 Unix 系统。