我正在编写有关多线程的代码。
我想从stdin接收一个字符串,并从n个工作线程处理它。
但是有一个问题。
使用ind = 0进行'pthread_join'时,所有线程都将加入。
此后,ind不变。
我对'pthread_join'错误吗?
出什么问题了?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#define BUFSIZE 8192
int n;
void *w_function(void *data)
{
printf("Here is : %d\n",*((int*)data));
pthread_exit(0);
}
int main(int ac, char* av[]){
pthread_t *w_thread;
int thr_id;
int i;
int status;
char ch;
char buf[BUFSIZE];
int ind=0, buf_ind;
int *count;
n=atoi(av[2]); // the number of thread
printf("%d\n",n);
w_thread=(pthread_t*)malloc(sizeof(pthread_t)*n); // thread n
count=(int*)malloc(sizeof(int)*n);
for(int i=0;i<n;i++) count[i]=i;
while(EOF != (buf[buf_ind]=fgetc(stdin))){
if( '\n' == buf[buf_ind] ){
printf("\\n in and to %d\n",ind);
buf[++buf_ind]='\0';
printf("before update: %d\n",ind);
pthread_join(w_thread[ind], (void **)&status);
thr_id = pthread_create(&w_thread[ind], NULL, w_function,(void*)&count[ind]);
if (thr_id < 0)
{
printf("thread create error : ");
exit(0);
}
printf("after update: %d\n\n",ind=(ind+1)%n);
buf_ind=0;
}
else buf_ind++;
}
return 0;
}
这是实际结果。
cat ./testdata.txt | ./homework_ver5 -n 5
5
\n in and to 0
before update: 0
after update: 1
\n in and to 1
before update: 1
after update: 2
\n in and to 2
before update: 2
after update: 3
\n in and to 3
before update: 3
after update: 4
\n in and to 4
before update: 4
after update: 0
\n in and to 0
before update: 0
Here is : 4
Here is : 3
Here is : 2
Here is : 1
Here is : 0
after update: 1
\n in and to 1
before update: 1
after update: 1
\n in and to 1
before update: 1
Here is : 0
after update: 1
\n in and to 1
before update: 1
Here is : 0
Here is : 0
after update: 1
\n in and to 1
before update: 1
Here is : 0
after update: 1
\n in and to 1
before update: 1
Here is : 0
after update: 1
\n in and to 1
before update: 1
Here is : 0
after update: 1
...