简体   繁体   中英

Passing two arguments with Pthreads in C

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;

}

如果你想使用 POSIX 线程,你需要向编译器添加-lpthread标志,这样你就可以用这种方式编译整个程序:

gcc -o main main.c -lpthread

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