繁体   English   中英

如何从pthreads中的每个线程依次打印?

[英]How to print from each thread in pthreads in order?

我正在为一个类程序编写程序,该程序采用Floyd-Warshall定向图(由矩阵表示),并为图中的每个节点创建一个新的距离矩阵,将使用pthreads在线程之间创建新矩阵的工作分开。 我觉得我最后是对的,我可以使矩阵形成并打印,但是我似乎无法弄清楚如何按顺序打印距离矩阵(首先由线程0创建的矩阵行,然后是线程线程1,线程2等)。 我使用互斥锁允许每个线程一起打印其零件而不会中断,只是无法按顺序打印线程。

我想知道那里的pthread专家是否会帮助我。 提前致谢!

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>

int n, totaln, **C, **D;                    /* Variable declarations */
pthread_t *threads;
pthread_mutex_t mutexprint;
long thread, threadcount;

void *LowestTerm(void* rank);

int main(int argc, char *argv[]) {

    int i, j, k;                        /* Variable declarations */
    char filename[50];

    threadcount = atoi(argv[1]);
    threads = malloc (threadcount * sizeof(pthread_t));

    printf("Enter filename: ");             /* User enters filename for directed graph values */
    scanf("%s", filename);

    FILE *fp = fopen(filename, "r");

    if (fp == NULL) {                   /* Check whether file exists or not */
        printf("File does not exist");
        return 1;
    }

    fscanf(fp, "%d", &n);                   /* Obtain size of matrix */

    totaln = n * n;

    C = (int **)malloc(n * sizeof(int *));          /* Allocate memory for matrix arrays */
    D = (int **)malloc(n * sizeof(int *));

    for (i = 0; i < n; i++) {               /* Allocate matrices into 2D arrays */
        C[i] = (int *)malloc(n * sizeof(int));
        D[i] = (int *)malloc(n * sizeof(int));
    }


    for (i = 0; i < n; i++) {               /* Read matrix from file into C array */
        for (j = 0; j < n; j++) {
            fscanf(fp, "%d", &C[i][j]);
        }
    }

    printf("Cost Adjacency Matrix:\n");         /* Print cost adjacency matrix */
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            printf("%d ", C[i][j]);
        }
        printf(" \n");
    }

    for (i = 0; i < n; i++) {               /* Copy matrix from C array into D array */
        for (j = 0; j < n; j++) {
            D[i][j] = C[i][j];
        }
    }

    printf("Distance matrix:\n");



    for (thread = 0; thread < threadcount; thread++) {
        pthread_create(&threads[thread], NULL, LowestTerm, (void*) thread);
    }
    for (thread = 0; thread < threadcount; thread++) {
        pthread_join(threads[thread], NULL);
    }

    pthread_mutex_destroy (&mutexprint);
    free(threads);
    pthread_exit(NULL);

}


void *LowestTerm(void* rank) {

    int i, j, k;                        /* Variable declarations */
    long mythread = (long) rank;

    int istart = ((int)mythread * n) / (int)threadcount;    /* Create matrix row start and finish parameters for each thread */
    int ifinish = ((((int)mythread + 1) * n) / (int)threadcount);

    for (k = 0; k < n; k++) {               /* Find shortest path for each value in each row for each of designated thread's rows */
        for (i = istart; i < ifinish; i++) {
            for (j = 0; j < n; j++) {
                if (D[i][j] > D[i][k] + D[k][j]) {
                    D[i][j] = D[i][k] + D[k][j];
                }
            }
        }
    }

    pthread_mutex_lock (&mutexprint);           /* Print distance matrix */
    for (i = istart; i < ifinish; i++) {
        printf("Thread %d: ", mythread);
        for (j = 0; j < n; j++) {
            printf("%d ", D[i][j]);
        }
        printf(" \n");
    }
    pthread_mutex_unlock (&mutexprint);


    return NULL;
}

最简单的解决方案是在所有辅助线程完成后,让您的主线程按所需顺序打印整个矩阵。


或者,要按顺序打印线程,可以使用共享变量,该变量指定要打印的下一个线程(初始化为0),并与条件变量配对:

pthread_mutex_lock (&mutexprint);           /* Print distance matrix */
while (next_thread != mythread)
    pthread_cond_wait(&condprint, &mutexprint);

for (i = istart; i < ifinish; i++) {
    printf("Thread %d: ", mythread);
    for (j = 0; j < n; j++) {
        printf("%d ", D[i][j]);
    }
    printf(" \n");
}

next_thread++;
pthread_cond_broadcast(&condprint);
pthread_mutex_unlock (&mutexprint);

作为单独的问题,我不认为您的线程安全地共享D[]数组-似乎从D[k][j]读取的内容可能正在读取由另一个线程同时写入的位置。

since each thread has a parameter that indicates its' rank,
the mutex could be on a global variable that indicates 
which thread/rank is to print next.
initialize it to 0.
each thread reads the global variable, after the thread
is ready to print
when the global variable matches the threads' rank, 
then the thread can:
1) lock the mutex, 
2) print, 
3) increment the global variable, 
4) unlock the mutex
5) call pthread_exit()

BTW: why are thread and threadcount defined as 'long'?
are you expecting there to be more than 4 gig threads?

at the end of function: LowestTerm()
which is a thread function.
the proper exit is not 'return value;'\
but rather phread_exit( value );

'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM