Thread Creation
#include <pthread.h> int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
-
thread: pthread_t structure type pointer points to, and the thread for interaction
- attr: thread is used for specifying the related properties, generally set to NULL, the default attributes
- start_routine: function specified thread running, for example, if the argument is int, return int, then it should be: int (* start_routine) (int)
- arg: argument specifies thread function
Thread to finish
#include <pthread.h> int pthread_join(pthread_t thread, void **retval);
-
thread: the specified thread to wait
-
retval: point you want to get the return value
Example:
#include <pthread.h> #include <stdio.h> #include <stdlib.h> void *mythread(void *arg) { int m = (int)arg; printf("%d\n", m); return (void *)(arg + 1); } int main(int argc, char *argv[]) { pthread_t p; int rc, m; pthread_create(&p, NULL, mythread, (void *)100); pthread_join(p, (void **) &m); printf("returned %d\n", m); return 0; }
result:
[zf@localhost ch27]$ ./main 100 returned 101
lock
pthread_mutex lock; pthread_mutex_lock(&lock); x=x+1; pthread_mutex_unlock(&lock);
Probably the code shown above normal, when pthread_mutex_lock call, if no other thread holds the lock, you can acquire the lock and enter the critical section, if another thread holds, then wait.
Note: There are two problems above
The first question: lock uninitialized
// two ways // 1. The lock is set to the default value pthread_mutex_t Lock = PTHREAD_MUTEX_INITIALIZER; // 2. dynamic initialization int RC = the pthread_mutex_init (& Lock , NULL); Assert (RC == 0 );
The second question: to acquire the lock and release the lock did not check the error code
int rc = pthread_mutex_lock(&lock); assert(rc == 0);
Condition variable
//线程1 pthread_mutex_lock(&lock); while (ready == 0) pthread_cond_wait(&cond, &lock); pthread_mutex_unlock(&lock); //线程2 pthread_mutex_lock(&lock); ready = 1; pthread_cond_signal(&cond); pthread_mutex_unlock(&lock);
When pthread_cond_wait the thread 1 2 sends a signal to enter dormancy, thread, so as to awaken the thread 1, note that signals the need to ensure that there is a lock. Finally, while more safe and effective than if.