使用互斥锁实现字符串的逆置

#include 【使用互斥锁实现字符串的逆置】#include #include #include #include #include typedef void *(*pthread_func_t) (void *); pthread_mutex_t mutex; char buf[] = "hello world"; pthread_mutex_t mutex; static int g_count = 0; void *read_string(void *arg) { //sleep(1); while(1){ pthread_mutex_lock(&mutex); printf("strings:%s\n",(char *)arg); //while(1); pthread_mutex_unlock(&mutex); printf("---------start reverse---%d---\n", g_count++); sleep(1); if(g_count == 5) break; } pthread_exit("read_ok"); }void *reverse_string(void *arg) { int i ; int length = strlen((char *)arg); usleep(100); while(1) { pthread_mutex_lock(&mutex); for(i = 0 ; i < length/2 ; i++) { ((char *)arg)[i] ^= ((char *)arg)[length - i - 1]; ((char *)arg)[length - i - 1] ^= ((char *)arg)[i]; ((char *)arg)[i] ^= ((char *)arg)[length - i - 1]; usleep(100); } pthread_mutex_unlock(&mutex); if(g_count == 5) break; } pthread_exit("reverse buff is ok!"); }int main(int argc, char const *argv[]) { int i , ret ; pthread_t tid_arr[2]; void *ret_arr[2]; pthread_func_t func[2] = {read_string, reverse_string}; pthread_mutex_init(&mutex, NULL); for(i = 0; i < 2 ; i++) { ret = pthread_create(&tid_arr[i], NULL, func[i], (void *)buf); if(ret < 0) { perror("pthread_create"); return ret; } } for(i = 0; i < 2 ; i++) { ret = pthread_join(tid_arr[i], &ret_arr[i]); if(ret < 0) { perror("pthread_join"); return ret; }printf("pthread %d : %s\n", i, (char *)ret_arr[i]); } pthread_mutex_destroy(&mutex); return 0; }

测试结果 使用互斥锁实现字符串的逆置
文章图片

    推荐阅读