在C语言中,实现多线程的方法主要有两种:一种是使用POSIX线程库(pthread),另一种是使用Windows API,下面分别介绍这两种方法的实现过程。

(图片来源网络,侵删)
1、使用POSIX线程库(pthread)
POSIX线程库是一套通用的多线程API,可以在多种平台上使用,包括Linux、Unix和macOS等,要在C语言中使用pthread库,需要先包含头文件<pthread.h>。
以下是一个简单的多线程程序示例:
#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;
}
在这个示例中,我们首先包含了<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>。
以下是一个简单的多线程程序示例:
#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;
}
在这个示例中,我们首先包含了<windows.h>头文件,然后定义了一个名为print_hello的函数,该函数将在新线程中执行,在main函数中,我们使用CreateThread函数创建了两个线程thread1和thread2,并分别调用这两个函数来启动这两个线程。CreateThread函数的前五个参数分别是:新线程的安全属性、堆栈大小、新线程要执行的函数、传递给新线程的参数以及一个指向返回值的变量;最后一个参数是一个指向线程ID的变量,我们使用WaitForSingleObject函数等待两个线程执行完毕,注意,在使用完线程句柄后,需要使用CloseHandle函数关闭它,如果使用了动态内存分配,还需要在退出前释放内存空间,这里假设print_hello是在堆上分配的,因此在退出前需要使用free函数释放内存空间。



评论(0)