创建两个线程,从标准输入获得字符串。这两个线程会交替获得字符串。请问这种情况的 是因为程序是互斥的访问标准输入缓冲的么?
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <time.h>
#include <windows.h>
void *InputEventTreadFunction(void *a)
{
while(1)
{
char c[10];
scanf("%s", c);
printf("%d:%s\n", *(int *)a, c);
}
return NULL;
}
int main()
{
int id1 = 1;
int id2 = 2;
pthread_t tTreadID1;
pthread_t tTreadID2;
int er = pthread_create(&tTreadID1, NULL, InputEventTreadFunction, &id1);
er = pthread_create(&tTreadID2, NULL, InputEventTreadFunction, &id2);
void* ptr;
pthread_join(tTreadID1, &ptr);
printf("tTreadID1\n");
pthread_join(tTreadID2, &ptr);
printf("tTreadID2\n");
return 0;
}
有没有试过三个线程
这个是操作系统的概念了,当有线程执行到scanf("%s", c);标准输入就会等待你的键盘输入。在你按下回车前也就是释放标准输入的锁之前,其他线程运行到scanf("%s", c);时就会阻塞,而阻塞的线程是会放到一个(阻塞)队列中,释放锁资源后候也是先阻塞的先唤醒。假如id1先抢到标准输入,后续id2,id3,id4...依次阻塞。除非你敲键盘的速度比CPU运行速度快,否则改变不了第一次的顺序。而创建线程也是要时间的,理论上先创建的,其运行进度会快些。但是想看线程第一次抢资源的话可以这么搞,让创建好了所有线程再一起执行
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <time.h>
#include <windows.h>
int lock ;
void *InputEventTreadFunction(void *a)
{
while(1)
{
if(lock != 1)
continue;
char c[10];
scanf("%s", c);
printf("%d:%s\n", *(int *)a, c);
}
return NULL;
}
int main() {
int id1 = 1;
int id2 = 2;
int id3 = 3;
int id4 = 4;
int id5 = 5;
pthread_t tTreadID1;
pthread_t tTreadID2;
pthread_t tTreadID3;
pthread_t tTreadID4;
pthread_t tTreadID5;
lock = 0;
int er = pthread_create(&tTreadID1, NULL, InputEventTreadFunction, &id1);
er = pthread_create(&tTreadID2, NULL, InputEventTreadFunction, &id2);
er = pthread_create(&tTreadID3, NULL, InputEventTreadFunction, &id3);
er = pthread_create(&tTreadID4, NULL, InputEventTreadFunction, &id4);
er = pthread_create(&tTreadID5, NULL, InputEventTreadFunction, &id5);
lock = 1;
void* ptr;
pthread_join(tTreadID1, &ptr);
printf("tTreadID1\n");
pthread_join(tTreadID2, &ptr);
printf("tTreadID2\n");
pthread_join(tTreadID2, &ptr);
printf("tTreadID3\n");
pthread_join(tTreadID2, &ptr);
printf("tTreadID4\n");
pthread_join(tTreadID2, &ptr);
printf("tTreadID5\n");
return 0;
}