1. Process creation
int Pthread_create (pthread_t * thread_id, __const pthread_attr_t * __attr, void * (*__start_routine) (void *), void *__res Trict __arg);
The first argument is a pointer to the thread identifier, the second parameter sets the Thread property, the third argument is the starting address of the thread's running function, and the last parameter is the argument that runs the function.
An example:
void *producer (void *args);
pthread_t tha;
Pthread_create (&tha,null,producer,null);
Pthread_join (Tha,null);
2, Mutual exclusion lock
Synchronization between threads is achieved through the locking mechanism. Only one thread is allowed to execute a key part of the code at the same time.
int Pthread_mutex_lock (pthread_mutex_t *mutex);
int Pthread_mutex_unlock (pthread_mutex_t *mutex);
An example:
pthread_mutex_t lock;
pthread_mutex_init (&lock, NULL);
pthread_mutex_lock (&lock);
Critical section
pthread_mutex_unlock (&lock);
3. Condition variables
A mechanism for synchronizing with global variables shared between threads, usually in conjunction with mutex locks.
int pthread_cond_wait (pthread_cond_t *cond,pthread_mutex_t *mutex); The function is to be used within the lock area of the mutex
int pthread_cond_signal (pthread_cond_t *cond);
An example:
pthread_cond_t Notfull;
Pthread_mutex_lock (&lock);
Pthread_cond_wait (¬full,&lock);
Pthread_mutex_unlock (&lock);
4. Signal Volume
#include <semaphore.h>
int Sem_init (sem_t *sem, int pshared, unsigned int value);
int sem_wait (sem_t *sem); Give the semaphore minus 1, call sem_wait for a semaphore with a value of 0, and the function will wait until there are other threads that make it no longer 0.
int Sem_post (sem_t *sem); Add 1 to the semaphore value
int Sem_destroy (sem_t *sem);
An example:
sem_t empty;
Sem_t occupied; These two variables are global variables
Sem_wait (&empty);
...
Sem_post (&occupied);
Mutual exclusion Lock, condition variable, semaphore of multi-threaded programming under Linux