c语言怎么实现多线程

在C语言中,实现多线程的方法主要有两种:一种是使用POSIX线程库(pthread),另一种是使用Windows API,下面分别介绍这两种方法的实现过程。,1、使用POSIX线程库(pthread),POSIX线程库是一套通用的多线程API,可以在多种平台上使用,包括Linux、Unix和macOS等,要在C语言中使用pthread库,需要先包含头文件
<pthread.h>。,以下是一个简单的多线程程序示例:,在这个示例中,我们首先包含了
<pthread.h>头文件,然后定义了一个名为
print_hello的函数,该函数将在新线程中执行,在
main函数中,我们创建了两个线程
thread1
thread2,并分别调用
pthread_create函数来启动这两个线程。
pthread_create函数的第一个参数是一个指向
pthread_t类型的指针,用于存储新创建的线程的ID;第二个参数是一个指向
pthread_attr_t类型的指针,用于设置线程的属性;第三个参数是新线程要执行的函数;第四个参数是传递给新线程的参数,我们使用
pthread_join函数等待两个线程执行完毕。,2、使用Windows API,Windows API提供了一套用于创建和管理线程的函数,主要包括
CreateThread
ExitThread
WaitForSingleObject等,要在C语言中使用Windows API,需要包含头文件
<windows.h>。,以下是一个简单的多线程程序示例:,在这个示例中,我们首先包含了
<windows.h>头文件,然后定义了一个名为
print_hello的函数,该函数将在新线程中执行,在
main函数中,我们使用
CreateThread函数创建了两个线程
thread1
thread2,并分别调用这两个函数来启动这两个线程。
CreateThread函数的前五个参数分别是:新线程的安全属性、堆栈大小、新线程要执行的函数、传递给新线程的参数以及一个指向返回值的变量;最后一个参数是一个指向线程ID的变量,我们使用
WaitForSingleObject函数等待两个线程执行完毕,注意,在使用完线程句柄后,需要使用
CloseHandle函数关闭它,如果使用了动态内存分配,还需要在退出前释放内存空间,这里假设
print_hello是在堆上分配的,因此在退出前需要使用
free函数释放内存空间。,
,#include <stdio.h> #include <pthread.h> void *print_hello(void *arg) { printf(“Hello from thread %ld! “, (long)arg); return NULL; } int main() { pthread_t thread1, thread2; int rc1, rc2; // 创建两个线程 rc1 = pthread_create(&thread1, NULL, print_hello, (void *)1); if (rc1) { printf(“Error: Unable to create thread 1 “); return 1; } rc2 = pthread_create(&thread2, NULL, print_hello, (void *)2); if (rc2) { printf(“Error: Unable to create thread 2 “); return 2; } // 等待两个线程执行完毕 pthread_join(thread1, NULL); pthread_join(thread2, NULL); return 0; },#include <stdio.h> #include <windows.h> DWORD WINAPI print_hello(LPVOID arg) { printf(“Hello from thread %d! “, *((int *)arg)); return 0; } int main() { HANDLE thread1, thread2; DWORD threadId1, threadId2; int arg1 = 1, arg2 = 2; // 创建两个线程 thread1 = CreateThread(NULL, 0, print_hello, &arg1, 0, &threadId1); if (thread1 == NULL) { printf(“Error: Unable to create thread 1 “); return 1; } thread2 = CreateThread(NULL, 0, print_hello, &arg2, 0, &threadId2); if (thread2 == NULL) { printf(“Error: Unable to create thread 2 “); return 2; } // 等待两个线程执行完毕 WaitForSingleObject(thread1, INFINITE); WaitForSingleObject(thread2, INFINITE); // 关闭线程句柄和退出线程函数的地址空间(可选) CloseHandle(thread1); CloseHandle(thread2); free(print_hello); // 如果使用了动态内存分配,需要在退出前释放内存空间,这里假设print_hello是在堆上分配的。 return 0; },

版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权
文章名称:《c语言怎么实现多线程》
文章链接:https://zhuji.vsping.com/471018.html
本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。