1
int S1 = 0;
int S2 = 0;
int x = 0;
int run = 1;
void Producer(void) {
    while(run) {
    while (S1 == S2);
    x++;
    __sync_synchronize();
    S1 = S2;
    __sync_synchronize();
    }
}

void Consumer(void) {
    while(run) {
    while (S1 != S2);
    x--;
    __sync_synchronize();
    S1 = !S2;
    __sync_synchronize();
    }
}

void* Worker(void *func) {
    long func_id = (long)func & 0x1;
    printf("%s %d\n",__func__, (int)func_id);
    switch (func_id) {
    case 0:
    Producer();
    break;
    case 1:
    Consumer();
    break;
    }
    return NULL;
}

int main(int argc, char *argv[]) {
     pthread_t t[argc];
     pthread_attr_t at;
     cpu_set_t cpuset;
     int threads;
     int i;
    #define MAX_PROCESSORS 4 // Minimal processors is 2.
     threads = argc > 1 ? (( atoi(argv[1]) < 4) ? atoi(argv[1]): MAX_PROCESSORS ) : 1;
    
     
     for (i = 0;i < threads; i++){ 
        CPU_ZERO(&cpuset);
        CPU_SET(i, &cpuset);
        pthread_attr_init(&at);
        
        (&at, sizeof(cpuset), &cpuset);
        if (pthread_create(&t[i], &at , Worker, (void *) (long)i) ) {
        perror("pthread create 1 error\n"); }
     }
     
     do {
        sleep(1);
     } while(x < 0);
     
    run = 0;
    void *val;
    for(i = 0; i < threads; i++)
    pthread_join(t[i], &val);
    printf("x=%d\n", x);
}

问题:在 ex1.c (6.1) 中,以下哪些属性实现了:

(一)互斥而不进步

(二)进步而不是相互排斥

(3) 既不互斥也不进步

(四)互斥与进步并重

请解释?

1.2

哪些论点(在 6.1 中)是正确的,哪些不正确:

(1) 总是退出。当线程 = 2 或线程 <= 0

(2) 总是挂起。线程 = 1 或线程 > 2

任何帮助将不胜感激

4

0 回答 0