日期:2014-05-16  浏览次数:20743 次

多线程 getline 问题 在线等
// test.c
#include <pthread.h>
#include <stdio.h>

pthread_mutex_t the_mutex;

void* routine(void *arg)
{
  char *line = NULL;
  size_t len = 0;
  size_t nread = 0;
  pthread_mutex_lock(&the_mutex);
  while ((nread = getline(&line, &len, stdin)) != -1) {
  pthread_mutex_unlock(&the_mutex);
  printf("%s", (char*)arg);
  // sleep(1);
  }
   
}

int main(void)
{
  pthread_mutex_init(&the_mutex, NULL);

  int tid1, tid2;
  void *tret;

  pthread_create(&tid1, NULL, routine, (void*)"111");
  pthread_create(&tid2, NULL, routine, (void*)"222");

  pthread_join(tid1, &tret);
  pthread_join(tid2, &tret);
}

我的目的是将来通过 cat 1.txt | ./test 方式运行,希望通过两个线程去读管道左边的输入,每次读一行。但是好像只有一个线程在运作,另一个线程根本不运作(通过打印来看),开始以为是巧合,但是经过大量测试,问题依然存在。而且在加sleep函数后,都不输出了,就卡在那里了,不知道,什么原因。请大家帮忙看看。

------解决方案--------------------
void* routine(void *arg)
{
char *line = NULL;
size_t len = 0;
size_t nread = 0;
while(1){
pthread_mutex_lock(&the_mutex);
if ((nread = getline(&line, &len, stdin)) == -1) {
pthread_mutex_unlock(&the_mutex);
break;
}
printf("%s", (char*)arg);
pthread_mutex_unlock(&the_mutex);
sleep(1);
}
}


------解决方案--------------------

第一个问题应该和线程调度有关;找个大一点的文件测试,会发现两个线程还是交替运行的。
想让一个线程让出CPU,最好使用 pthread_yield();使用 sleep()不敢保证没有问题。

C/C++ code

// test.c
#include <pthread.h>
#include <stdio.h>

pthread_mutex_t the_mutex;

void* routine(void *arg)
{
  char *line = NULL;
  size_t len = 0;
  size_t nread = 0;
  pthread_mutex_lock(&the_mutex);
  printf("get the lock for %s\n", (char *)arg);
  while ((nread = getline(&line, &len, stdin)) != -1) 
  {
  pthread_mutex_unlock(&the_mutex);
  printf("%s", (char*)arg);
  pthread_yield();
  pthread_mutex_lock(&the_mutex);
  }
  pthread_mutex_unlock(&the_mutex);
}

int main(void)
{
  pthread_mutex_init(&the_mutex, NULL);

  int tid1, tid2;
  void *tret;

  pthread_create(&tid1, NULL, routine, (void*)"111");
  pthread_create(&tid2, NULL, routine, (void*)"222");

  pthread_join(tid1, &tret);
  pthread_join(tid2, &tret);
}

------解决方案--------------------
我看了很久,也看了上面几位大神的回答,我觉得没有那么复杂把! 楼主想从打印来看,可是你用printf没有加换行符.