簡體   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