1.创建线程
res = pthread_create(&a_thread, NULL, thread_function1, NULL);
if (res != 0)
{
perror("Thread creation failure");
}
2.等待线程结束
pthread_join
3.线程退出时,语句:
pthread_exit(NULL);
return NULL;
4. 互斥锁 使用前必须初始化!!!
pthread_mutex_init(&mutex, NULL);
pthread_mutex_destroy(&mutex);
4.
#include <stdio.h> #ifdef _WIN32 #include <windows.h> #include <stdio.h> #define sleep Sleep #else #include <unistd.h> #endif #include <stdlib.h> #include <string.h> #include <pthread.h> #include <semaphore.h> sem_t bin_sem; void *thread_function1(void *arg) { printf("thread_function1--------------sem_wait "); sem_wait(&bin_sem); printf("sem_wait OK "); while (1) { } pthread_exit(NULL); return NULL; } void *thread_function2(void *arg) { printf("thread_function2--------------sem_post "); sem_post(&bin_sem); printf("sem_post "); while (1) { } return NULL; } int main() { int res; pthread_t a_thread; void *thread_result; res = sem_init(&bin_sem, 0, 0); if (res != 0) { perror("Semaphore initialization failed"); } printf("sem_init "); res = pthread_create(&a_thread, NULL, thread_function1, NULL); if (res != 0) { perror("Thread creation failure"); } printf("thread_function1 "); sleep (5); printf("sleep "); res = pthread_create(&a_thread, NULL, thread_function2, NULL); if (res != 0) { perror("Thread creation failure"); } while (1) { } }
5 sem:
sem_post 每执行一次 则加1
sem_wait( &st ) 等待直到st大于1 才向下执行, 每次执行st减去1;
6 条件锁
#include <pthread.h> #include <stdio.h> #ifdef _WIN32 #include <windows.h> #define sleep(p) Sleep(p) #else #include <ustlib.h> #define sleep(p) usleep((p)*1000) #endif pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; /*初始化互斥锁*/ pthread_cond_t cond = PTHREAD_COND_INITIALIZER; //初始化条件变量 void *thread1(void *); void *thread2(void *); int i = 1; int main(void) { pthread_t t_a; pthread_t t_b; pthread_create(&t_a, NULL, thread1, (void *)NULL);/*创建进程t_a*/ pthread_create(&t_b, NULL, thread2, (void *)NULL); /*创建进程t_b*/ pthread_join(t_b, NULL);/*等待进程t_b结束*/ pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); getchar(); exit(0); } void *thread1(void *junk) { for (i = 1; i <= 9; i++) { pthread_mutex_lock(&mutex);// if (i % 3 == 0) pthread_cond_signal(&cond);/*条件改变,发送信号,通知t_b进程*/ else printf("thead1:%d ", i); pthread_mutex_unlock(&mutex);//*解锁互斥量*/ printf("Up Unlock Mutex "); sleep(1); } return NULL; } void *thread2(void *junk) { while (i<9) { pthread_mutex_lock(&mutex); if (i % 3 != 0) pthread_cond_wait(&cond, &mutex);/*等待*/ printf("thread2:%d ", i); pthread_mutex_unlock(&mutex); printf("Down Ulock Mutex "); sleep(1); } return NULL; }