开发者

C Pthreads Problem, Can't Pass the Info I Want?

So I'm trying to make it so the threads startup function opens a file that was given via commandline, one file for each thread, but I also need the star开发者_如何学运维tup function to get my results array. So basically I need to get a string (the filename) and a 2D array of results to my startup thread some how, I'm thoroughly confused.

Anyone have any tips or ideas? Thanks.

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include "string.h"


void* func(void *args);

int main(int argc, const char * argv[])
{
    int nthreads = 0;
    int i = 0;
    long **results;

    printf("Enter number of threads to use:\n> ");
    scanf("%d", nthreads);

    pthread_t threadArray[nthreads];

    // results 2d array; 3 rows by nthreads cols
    results = malloc((nthreads*4) * sizeof(long *));   

    for(i = 0; i<nthreads; i++) {
       pthread_create(&threadArray[i], NULL, wordcount, HELP!!!!); 
    } 

    for(i = 0; i<nthreads; i++) {
       pthread_join(threadArray[i], NULL);
    } 

    pthread_exit();
}

void * func(void *arguments)
{     
     FILE *infile = stdin;
     infile = fopen(filename, "rb");    

     fclose (infile);
}


Generally a structure that contains the data for the thread is declared and initialized, and a pointer to that structure is passed as the thread argument.

The thread function then casts the void* back to the structure pointer and has at the data.

Just remember that the lifetime of that structure still needs to be valid when the thread gets scheduled (which means you need to be very careful if it's a local variable). And as Jonathan Leffler pointed out, pass each thread it's own instance of the structure, or be very careful how you reuse it. Otherwise a thread may read data intended for a different thread if the structure gets reused before the thread is finished with it.

Probably the simplest way to manage those issues is to malloc() a structure for each thread, initialize it, pass the pointer to the thread and let the thread free() it when it's done with the data.


The last parameter to pthread_create can be any object you want, so for example you could have:

struct ThreadArguments {
    const char* filename;
    // additional parameters
};

void* ThreadFunction(void* arg) {
    CHECK_NOTNULL(arg);
    ThreadArguments* thread_arg = (ThreadArguments*) arg;
    // now you can access the other parameters through this thread_arg object
    // ...
}

// ...
ThreadArguments* arg = (ThreadArguments*) malloc(sizeof(ThreadArguments));
ret = pthread_create(&thread_id, attributes, &ThreadFunction, arg);
// make sure to check ret
// ...
pthread_join(thread_id);
free(arg);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜