线程使用:
int com_index=1;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
int thread_run(void * ins){
if (pthread_mutex_lock(&mutex)!=0){
LOGI("***lock error");
return -1;
}
const char *outs= static_cast<const char *>(ins);
sleep(4);
com_index+=1;
LOGI("***run:%d---%s", com_index, outs);
if (pthread_mutex_unlock(&mutex)!=0){
LOGI("***unlock error");
return -1;
}
return 0;
}
void thread_test(){
// code start
pthread_t pthread;
const char* ins="input args";
int ret=pthread_create(&pthread, NULL, reinterpret_cast<void *(*)(void *)>(&thread_run), (void *) ins);
if (ret!=0){
LOGI("***init p error");
}
pthread_join(pthread, reinterpret_cast<void **>(&ret));
LOGI("***fire end%d", ret);
}
信号量使用:
sem_t sem;
void thread_run2(void){
sleep(3);
sem_post(&sem);
}
void sem_test(){
pthread_t pthread;
sem_init(&sem, 0, 0);
LOGI("***fire start");
int ret=pthread_create(&pthread, NULL, reinterpret_cast<void *(*)(void *)>(&thread_run2), NULL);
if (ret!=0){
LOGI("***init p error");
}
sem_wait(&sem);
LOGI("***fire end%d", ret);
sem_destroy(&sem);
}