我正在尝试线程编程练习(来自HERE)并进行一些调整。我想尝试2个(或更多)线程,一次从一个字符串读取一个字,然后写入缓冲区。最后主线程将打印线程写入的缓冲区。
即使我不使用互斥锁来保护写缓冲区,我的代码也能正常工作,我感到很惊讶?在目前的状态 - 这是正确的做事方式吗?它产生正确的输出。
特别是'Hello'函数中的while循环:如果使用互斥锁会更有效吗?在这种情况下如何编写代码?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
int threadCount = 3;
int finish = 0;
int turn = 0;
void *Hello(void *rank);
char *str = "This is a really long string.. such a long string this really is... !";
char buff[512];
int index = 0;
int main() {
long thread;
pthread_t *hThread;
hThread = (pthread_t *)malloc(threadCount*sizeof(pthread_t));
if(hThread == NULL) {
printf("\nERROR: malloc failed");
}
for(thread = 0; thread < threadCount; thread++) {
pthread_create(&hThread[thread], NULL, Hello, (void *)thread);
}
printf("Hello from main thread !\n");
for(thread = 0; thread < threadCount; thread++) {
pthread_join(hThread[thread], NULL);
}
printf("All threads finished !\n");
printf("%s\n", buff);
free(hThread);
return 0;
}
void printMsg(void) {
if(finish)
return;
while(*str != '\0' && *str != ' ') {
buff[index++] = *str;
printf("%c",*str++);
}
printf("\n");
if(*str == ' ') {
buff[index++] = ' ';
str++;
}
if(*str == '\0') {
buff[index++] = '\0';
finish = 1;
}
turn = (turn +1)%threadCount;
}
void *Hello(void *rank) {
long id = (long)rank;
while(!finish) {
if(turn == (int)id) {
printf("%ld : ", id);
printMsg();
}
}
return NULL;
}
我可以看到输出产生为:
0 : This
Hello from main thread !
1 : is
2 : a
0 : really
1 : long
2 : string..
0 : such
1 : a
2 : long
0 : string
1 : this
2 : really
0 : is...
1 : !
All threads finished !
This is a really long string.. such a long string this really is... !