When creating a lock, you must do two things:
- Initialize the lock
- Check if lock/unlock failed! (i.e. check the error code).
It’s common to use wrappers to do the checking for you.
Beginners often try to do this:
while (ready == 0); // spin
where ready is a global variable. The thread that has the lock will set ready to 1 when done.
This is a bad idea! It causes the CPU to use up cycles. And it is a very buggy model - you’ll often fail.
In gcc, to compile a multithreaded program, do:
gcc -o main main.c -Wall -pthread