#include<pthread.h> // initialize a mutex // mutex: // structure of mutex // mutexattr: // NULL is enough // return value: // return 0 for success, or non-zero errno on error intpthread_mutex_init(pthread_mutex_t *restrict mutex, constpthread_mutexattr_t *restrict attr);
// destroy a mutex // you should call the function to destroy all the mutexes // mutex: // structure of mutex // return value: // return 0 for success, or non-zero errno on error intpthread_mutex_destroy(pthread_mutex_t *mutex);
#include<pthread.h> // block to lock a mutex intpthread_mutex_lock(pthread_mutex_t *mutex) // try to lock a mutex non-blocked, return 0 on success or 16 if mutex is busy intpthread_mutex_trylock(pthread_mutex_t *mutex) // release a mutex intpthread_mutex_unlock(pthread_mutex_t *mutex)
intdone(){ pthread_mutex_lock(&mutex); // 上锁 int flag = i <= 100; if (flag) { printf("%ld\t%d\n", pthread_self(), i); i++; } pthread_mutex_unlock(&mutex); // s return flag; }
void *sale(void *arg){ while (done()); returnNULL; }
pthread_t tid[3]; for (int i = 0; i < 3; i++) { pthread_create(&tid[i], NULL, sale, NULL); } for (int i = 0; i < 3; i++) { pthread_join(tid[i], NULL); }