Home > front end >  Passing two arguments with Pthreads in C
Passing two arguments with Pthreads in C

Time:11-08

One of my school projects is to make a program that does multithreading. I have the code for my program already but I don't know how to multithread. So I decided to make a seperate program to have an idead of how multthreading works. My problem is I am trying to pass two arguments into pthreads and found out recently that I couldn't do that and I would have to pass a struct into pthreads to do that. My code is suppose to see if I can pass in the 1 and 2 from arguments structure into my pthread. The answer should print 3. I think I am close to figuring it out, but I keep getting this error

unresolved external symbol__imp__pthread_create referenced in function _main and unresolved external symbol __imp_pthread_join referenced in function _main

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HAVE_STRUCT_TIMESPEC
#include <pthread.h>



struct Arguments {
    int a;
    int b;
};

void* threadFunction(void*);

int main()
{

    struct Arguments arguments;
    arguments.a = 1;
    arguments.b = 2;

    void* ptr;

    printf("this is total outside of the function %d", *(int*)threadFunction(&arguments));

    pthread_t t1;

    pthread_create(&t1, NULL, &threadFunction, &arguments);
    pthread_join(t1, &ptr);

    return 0;
}

void* threadFunction(void* functionArguments) {

    struct Arguments arguments2;
    arguments2 = *(Arguments*)functionArguments;
    void* ptr;
    static int total;

    int a;
    int b;

    a = arguments2.a;
    b = arguments2.b;

    //lets try malloc for total
    total = a   b;

    printf("this is total inside of the function %d\n", total);
    ptr = &total;
    return ptr;

}

CodePudding user response:

You need to add the -lpthread flag to the compiler command line if you want to use POSIX threads. So, you can compile whole program in this way:

gcc -o main main.c -lpthread

CodePudding user response:

@DangLe stackoverflow savoir vivre requires to mark working answer as accepted Best regards

  • Related