Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

getting error in c program "undefined reference to gettid"

This is my thread sub routine... Here, I am creating 4 threads and passing structure as a argument to thread sub routine.

I am trying to print thread id with getid() function,

I am getting error saying "undefined reference to gettid()".

I have added necessary header files...

#include <pthread.h>
#include <stdio.h>
#include <sys/types.h>
#define ARRAYSIZE 17
#define NUMTHREADS 4

struct ThreadData {
        int start, stop;
        int* array; 
};

void* squarer(void* td) 
{
     struct ThreadData* data=(struct ThreadData*) td;

     int start=data->start;
     int stop=data->stop;
     int* array=data->array;
     int i;
     pid_t tid1;

     tid1 = gettid(); //error at this statement//`
     printf("tid : %d
",tid1);

     for (i=start; i<stop; i++) {
         sleep(1);
         array[i]=i*i;
         printf("arr[%d] = [%d]
",i,array[i]);
     } 
   return NULL;
}

int main(void) {
    int array[ARRAYSIZE];
    pthread_t thread[NUMTHREADS];
    struct ThreadData data[NUMTHREADS];
    int i;

    int tasksPerThread=(ARRAYSIZE+NUMTHREADS-1)/NUMTHREADS;

    for (i=0; i<NUMTHREADS; i++) {
            data[i].start=i*tasksPerThread;
            data[i].stop=(i+1)*tasksPerThread;
            data[i].array=array;
    }

    data[NUMTHREADS-1].stop=ARRAYSIZE;

    for (i=0; i<NUMTHREADS; i++) {
            pthread_create(&thread[i], NULL, squarer, &data[i]);
    }

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

    for (i=0; i<ARRAYSIZE; i++) {
            printf("%d ", array[i]);
    }
    printf("
");

    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try

#include <unistd.h>
#include <sys/syscall.h>

#ifdef SYS_gettid
pid_t tid = syscall(SYS_gettid);
#else
#error "SYS_gettid unavailable on this system"
#endif

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...