线程并发C程序



我用两个线程编写了一个C程序。第一个线程以最快的速度递增计数器,而第二个线程偶尔读取计数器值并打印其值。是否可以检查线程之间是否存在并发?

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdlib>

int counter = 0;
void* do_nothing(void *null) {
    while(true) {
        counter = counter % 10000000;
        counter++;
    }
} 
void* do_nothing1(void *null) {
    while(true) {
        if(rand()%10000000 == 5) printf("counter %dn", counter);
    }
}       
int main(int argc, char *argv[]) {
    pthread_t tid, tid1;
    pthread_attr_t attr; 
    pthread_attr_init(&attr);   
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
    if (pthread_create(&tid, &attr, do_nothing, NULL)) {              
        printf("ERROR; return code from pthread_create()");
        exit(-1);
    }
    if (pthread_create(&tid, &attr, do_nothing1, NULL)) {              
        printf("ERROR; return code from pthread_create()");
        exit(-1);
    }
    if (pthread_join(tid, NULL)) {
        printf("ERROR; return code from pthread_join()");
        exit(-1);
    }
    /*if (pthread_join(tid1, NULL)) {
        printf("ERROR; return code from pthread_join()1");
        exit(-1);
    }*/
    pthread_attr_destroy(&attr);
    pthread_exit(NULL);
    exit(0);
}

最简单的方法是在do_nothing()中使用printf()。顺便说一句,你有一些错误,但我可以告诉你,你还在学习。

最新更新