C怎么管理线程
C语言中管理线程需要使用相关的库,常用的线程库有pthread和Windows API。
- 使用pthread库
pthread是POSIX线程标准的实现之一,可以在多种操作系统上使用。通过pthread库,可以创建、控制和同步多个线程。
线程创建:
#include <pthread.h>
pthread_t thread_id;
void *thread_function(void *arg)
{
// 线程执行的代码
}
int main()
{
pthread_create(&thread_id, NULL, thread_function, NULL);
}
线程同步:
#include <pthread.h>
pthread_mutex_t mutex;
void *thread_function(void *arg)
{
pthread_mutex_lock(&mutex);
// 线程执行的代码
pthread_mutex_unlock(&mutex);
}
int main()
{
pthread_mutex_init(&mutex, NULL);
pthread_t thread_id;
pthread_create(&thread_id, NULL, thread_function, NULL);
pthread_mutex_lock(&mutex);
// 主线程执行的代码
pthread_mutex_unlock(&mutex);
}
- 使用Windows API
Windows API提供了一系列用于线程管理的函数,包括创建、控制和同步线程。
线程创建:
#include <windows.h>
DWORD WINAPI thread_function(LPVOID lpParam)
{
// 线程执行的代码
}
int main()
{
HANDLE thread_handle = CreateThread(NULL, 0, thread_function, NULL, 0, NULL);
}
线程同步:
#include <windows.h>
HANDLE mutex_handle;
DWORD WINAPI thread_function(LPVOID lpParam)
{
WaitForSingleObject(mutex_handle, INFINITE);
// 线程执行的代码
ReleaseMutex(mutex_handle);
}
int main()
{
mutex_handle = CreateMutex(NULL, FALSE, NULL);
HANDLE thread_handle = CreateThread(NULL, 0, thread_function, NULL, 0, NULL);
WaitForSingleObject(mutex_handle, INFINITE);
// 主线程执行的代码
ReleaseMutex(mutex_handle);
}
``
原文地址: https://www.cveoy.top/t/topic/fplu 著作权归作者所有。请勿转载和采集!