#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;
}
测试结果
文章图片
推荐阅读
- android|IPC方式(ContentProvider、Socket、Binder连接池)--《Android开发艺术探索》阅读笔记——第二章part4
- 使用线程的互斥锁实现生产者消费者模型
- 互斥锁与条件变量实现按照顺序打印ABC
- 使用三个线程下的信号量实现顺序打印ABC