0
线程对我而言是新的。我只是试过这样的代码线程无法正常工作
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
typedef struct{
sem_t *s;
int firstID;
int secondID;
} stadium;
void * game(void * currentData){
stadium * st = (stadium *)currentData;
sem_wait(st->s);
int first = st->firstID;
int second = st->secondID;
int o = rand();
int t = rand();
printf("%d Team %d:%d %d Team\n",first,o%100009,t%100009,second);
sem_post(st->s);
}
int main(){
for(int i= 1;i<=10;i++){
for(int j = i+1;j<=10;j++){
sem_t s ;
sem_t c;
sem_init(&s,0,4);
sem_init(&c,0,1);
pthread_t p;
stadium st;
st.firstID = i;
st.secondID = j;
st.s = &s;
st.counter = &c;
pthread_create(&p,NULL,game,&st);
}
}
pthread_exit(0);
return 0;
}
它随机打印,但不知何故它打印相同的对。当它只在同一对上迭代一次时,它如何打印同一对呢?
你传入* *不同的信号量给每个线程。这打破了信号量的目的,因为这意味着它们不会彼此同步。另外,信号量在'for'循环中被声明为*,因此它们在循环结束后超出范围(此时线程可能还没有运行)。最后,你的主线程不会等待子线程退出 - 所以它将在线程退出时终止所有线程。 – kaylum
'体育场st'。这也是一个传递给线程的自动变量,但是在子线程可能已经完成或未完成的时间超出了范围。也就是说,您的代码充满了未定义的行为和逻辑错误。 – kaylum
@kaylum主要会让其他线程完成。 – 2501