C语言标准库创建线程代码
时间: 2023-06-03 18:05:55 浏览: 115
可以使用C语言标准库中的pthread库来创建线程。以下是一个简单的例子:
```
#include <pthread.h>
#include <stdio.h>
void *myThreadFun(void *vargp)
{
printf("Thread created using pthread library!\n");
return NULL;
}
int main()
{
pthread_t thread_id;
printf("Before Thread\n");
pthread_create(&thread_id, NULL, myThreadFun, NULL);
pthread_join(thread_id, NULL);
printf("After Thread\n");
exit(0);
}
```
这个程序中,`pthread_create()`函数用于创建线程,并传入`myThreadFun`函数作为线程的入口点。`pthread_join()`函数用于等待线程执行完毕,使得主线程不会退出。
相关问题
windows c语言创建线程,不使用windows api
如果不使用 Windows API,可以使用 C 标准库中的 `pthread` 库来创建线程。具体步骤如下:
1. 引入头文件
```c
#include <pthread.h>
```
2. 定义线程函数
```c
void *myThread(void *arg) {
// 线程执行的代码
return NULL;
}
```
注意,线程函数的返回值为 `void *` 类型。
3. 创建线程
```c
pthread_t myThreadHandle;
pthread_create(&myThreadHandle, NULL, myThread, NULL);
```
其中,`pthread_create` 函数的第一个参数为输出线程句柄,第二个参数为线程属性,可以为 `NULL`,第三个参数为线程函数,第四个参数为传递给线程函数的参数,可以为 `NULL`。
4. 等待线程结束
```c
pthread_join(myThreadHandle, NULL);
```
其中,`pthread_join` 函数用于等待线程结束。
完整的示例代码如下:
```c
#include <stdio.h>
#include <pthread.h>
void *myThread(void *arg) {
printf("Thread is running...\n");
return NULL;
}
int main() {
pthread_t myThreadHandle;
pthread_create(&myThreadHandle, NULL, myThread, NULL);
pthread_join(myThreadHandle, NULL);
return 0;
}
```
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 系统。