在線程中,您可以使用mutex
來這樣做。
在POSIX,我們有pthread_mutex_t
解決方案:Full example
#include<pthread.h>
pthread_t tid[2];
pthread_mutex_t lock;
void* f(void *arg)
{
pthread_mutex_lock(&lock);
...
pthread_mutex_unlock(&lock);
}
void main(void)
{
pthread_mutex_init(&lock, NULL)
pthread_create(tid[0],..., f, ...);
pthread_create(tid[1],..., f, ...);
pthread_join(tid[0],...);
pthread_join(tid[1],...);
pthread_mutex_destroy(&lock);
}
然後在Windows線程,我們也有互斥方案:Full example
#include <windows.h>
int numThreads = 2;
HANDLE threadHandles[2];
HANDLE mutex = NULL;
void* f(void *arg)
{
WaitForSingleObject(mutex, INFINITE);
...
ReleaseMutex(mutex);
}
void main(void)
{
mutex = CreateMutex(NULL, FALSE, NULL);
threadHandles[0] = CreateThread(..., f, ...);
threadHandles[1] = CreateThread(..., f, ...);
WaitForMultipleObjects(numThreads, threadHandles, TRUE, INFINITE);
CloseHandle(threadHandles);
}