CodeBlanks Logo Icon CodeBlanks

Lock types

Learn the difference between shared and exclusive locks.

Shared and exclusive

There are two main lock types. A shared lock (LOCK_SH or F_RDLCK) allows multiple readers; it can be taken when no writer holds the lock. An exclusive lock (LOCK_EX or F_WRLCK) grants single ownership; it can be taken only when no other lock exists.

You take a shared lock for reading and an exclusive lock for writing. This rule prevents readers from seeing inconsistent data. If the same process reads and writes, an exclusive lock suffices. You can convert locks: first take LOCK_SH, then upgrade to LOCK_EX; releasing with LOCK_UN in between is the safest path.

Lock upgrade

Sometimes we first read, then write. We may want to take LOCK_SH first and then upgrade to LOCK_EX. Direct conversion may block on some systems; the safest path is to release with LOCK_UN and then take LOCK_EX.

For testing, you can take and release both lock types in sequence: flock(fd, LOCK_SH); printf("shared\n"); flock(fd, LOCK_UN); flock(fd, LOCK_EX); printf("exclusive\n"); flock(fd, LOCK_UN);. This clearly shows how shared and exclusive locks behave.

Practice Try both lock types

Open the file with int fd = open("/tmp/cb_types.txt", O_CREAT | O_RDWR, 0644);. Call flock(fd, LOCK_SH);, printf("shared\n");, flock(fd, LOCK_UN);. Then flock(fd, LOCK_EX);, printf("exclusive\n");, flock(fd, LOCK_UN);. close(fd); and unlink("/tmp/cb_types.txt");.

Starter code

main.c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/file.h>

// Open file
// Take shared lock, print, release
// Take exclusive lock, print, release, close and remove

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/file.h>

int main(void) {
    int fd = open("/tmp/cb_types.txt", O_CREAT | O_RDWR, 0644);
    flock(fd, LOCK_SH);
    printf("shared\n");
    flock(fd, LOCK_UN);
    flock(fd, LOCK_EX);
    printf("exclusive\n");
    flock(fd, LOCK_UN);
    close(fd);
    unlink("/tmp/cb_types.txt");
    return 0;
}

Expected output

shared
exclusive

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Shared lock

Question
flock(fd, ____);
Answer
flock(fd, LOCK_SH);

Explanation: LOCK_SH acquires a shared lock; suitable for reading.

2 Match lock types

Term Meaning
LOCK_SH Many readers
LOCK_EX Single writer
F_RDLCK Read lock
F_WRLCK Write lock

3 Which lock should be taken when writing?

  • Shared lock
  • No lock access
  • Exclusive lock Correct answer
  • Read lock only

Explanation: Writing requires an exclusive lock (LOCK_EX).

All lessons in Advanced