简体   繁体   中英

Using pthread_create

I am having errors when I try to use pthread_create. I understand that my use of argsRight->thread_id / argsLeft->thread_id and NULL are not correct, but I am unsure how else to make a reference to the thread id. It requires a pointer, but it seems like every way I tried (&, *), the GCC compiler would not accept.

Also, is there any reason it will not accept my use of NULL? I can't see any reason that would be wrong, but GCC says my use of the void function is invalid.

Can anyone shed some light on how to properly set up a call to pthread_create? I have included parts from my method where I am using the pthread_create function.

void pthreads_ms(struct ms_args* args)
{
int left_end = (args->end + args->start) / 2;
int right_start = left_end + 1;
int rc1, rc2;

// Create left side struct
struct ms_args* argsLeft;
argsLeft = malloc(sizeof(args));
argsLeft->thread_id = (2 * args->thread_id + 1);
argsLeft->start = args->start;
argsLeft->end = left_end;
argsLeft->array = args->array;

// Same methodology as above to create the right side

if (args->start != args->end)
{
        // Print the thread id number, and start and end places
            printf("[%d] start %d end %d", args->thread_id, args->start, args->end);

        // Sort Left Side
        rc1 = pthread_create(argsLeft->thread_id, NULL, pthreads_ms(argsLeft), argsLeft);   //problem line here

        //Sort right side
        rc2 = pthread_create(argsRight->thread_id, NULL, pthreads_ms(argsRight), argsRight); //problem line here
}

It is not your application, it's pthread_create() will fill thread_id field. So, first of all, struct ms_args 's field should be of type pthread_t and you should pass a pointer to that field:

pthread_create(&argsLeft->thread_id, ...

According to pthread_create the proper call should be

rc1 = pthread_create(&(argsLeft->thread_id), NULL, &pthreads_ms, argsLeft);

Same goes for right side.

The definition of pthread_ms() should include a return value

void *pthreads_ms(struct ms_args* args) { ... }

Besides that, your code looks pretty dangerous to me, since it creates recursively two threads for every existing one. Depending on your input, this might build a large tree of threads, which could bring your system to a halt.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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