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\n"); sem_wait(&bin_sem); printf("sem_wait OK\n"); while (1) { } pthread_exit(NULL); return NULL; } void *thread_function2(void *arg) { printf("thread_function2--------------sem_post\n"); sem_post(&bin_sem); printf("sem_post\n"); 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\n"); res = pthread_create(&a_thread, NULL, thread_function1, NULL); if (res != 0) { perror("Thread creation failure"); } printf("thread_function1\n"); sleep (5); printf("sleep\n"); res = pthread_create(&a_thread, NULL, thread_function2, NULL); if (res != 0) { perror("Thread creation failure"); } while (1) { } }
sem:
sem_post 每执行一次 则加1
sem_wait( &st ) 等待直到st大于1 才向下执行, 每次执行st减去1;