简体   繁体   中英

File locking between threads and processes

I have a program that spawns multiple processes or threads, each of which writes a line on the file, but obviously I don't want the line to get mixed up, so I need exclusive access to the file.

More specifically, in the first case, I have a process F which spawns several child processes (C1, C2, C3, C4, ...), and I want to block access from F, C2, C3, C4, ... when C1 is writing.

In the second case, I have the same process F which spawns several threads (T1, T2, T3, T4, ...) and, again, I want to block access from F, T2, T3, T4, ... when T1 is writing.

I'm guessing a function like flock() takes care of the first part, but what about the threads case? And what about the Windows platform?

You can use any locking mechanism you want. Between threads, a mutex is the simplest. Access to the file is protected by the mutex, so no two threads could try to write to the file at the same time.

For processes, you can use a process-shared mutex. On Windows, you can use a named mutex .

In thread, you can use mutex to do so.

In POSIX, we have pthread_mutex_t solution: 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);
}

Then in Windows thread, we also have mutex solution: 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM