pthread_create and passing an integer as the last argument
Asked Answered
A

6

48

I have the following functions :

void *foo(void *i) {
    int a = (int) i;
}

int main() {
    pthread_t thread;
    int i;
    pthread_create(&thread, 0, foo, (void *) i);
}

At compilation, there are some errors about casting ((void *) i and int a = (int) i). How can I pass an integer as the last argument of pthread_create properly?

Accent answered 7/10, 2013 at 19:27 Comment(0)
F
56

Building on szx's answer (so give him the credit), here's how it would work in your for loop:

void *foo(void *i) {
    int a = *((int *) i);
    free(i);
}

int main() {
    pthread_t thread;
    for ( int i = 0; i < 10; ++1 ) {
        int *arg = malloc(sizeof(*arg));
        if ( arg == NULL ) {
            fprintf(stderr, "Couldn't allocate memory for thread arg.\n");
            exit(EXIT_FAILURE);
        }

        *arg = i;
        pthread_create(&thread, 0, foo, arg);
    }

    /*  Wait for threads, etc  */

    return 0;
}

On each iteration of the loop, you're allocating new memory, each with a different address, so the thing that gets passed to pthread_create() on each iteration is different, so none of your threads ends up trying to access the same memory and you don't get any thread safety issues in the way that you would if you just passed the address of i. In this case, you could also set up an array and pass the addresses of the elements.

Foxtail answered 7/10, 2013 at 23:2 Comment(16)
I get this when I compile : error: invalid conversion from ‘void*’ to ‘int*’ at this line : int *arg = malloc(sizeof(*arg));. You should put (int *) before malloc.Accent
@Gradient: You must be compiling this as C++. The cast is not necessary in C and, to my mind, should not be included.Foxtail
I believe the statement int *arg = malloc(sizeof(*arg)); should instead be int *arg = malloc(sizeof(arg));. Here it works because a pointer on most machines is the size of int. However it may fail for other data types or even custom types. Correct me if I am wrong hereJustus
@Pegasus: you are incorrect. Here you want to be allocating the correct amount of space for an int, not for a pointer to int. Your alternative would do the latter, so it's actually your suggestion that would only work if pointers and ints are the same size.Foxtail
But doesn't this statement int *arg = malloc(sizeof(*arg)) in fact allocates space for a pointer rather a double pointer (consider *arg is in fact a pointer to a pointer to an int). I am still not convinced with your answer sirJustus
@Pegasus: No, it allocates space for an int. int * arg = malloc(sizeof(&arg)); would allocate space for a pointer to pointer to int. If you're "not convinced", then you're just confused about basic C syntax.Foxtail
I didn't mean to cause any offence. I'm just a beginner while you seem to be a veteran. Just expressed my thoughts. Nevertheless I'd like to know what arg means in the statement int * arg = malloc(sizeof(&arg));. To me it looks like an integer pointer and thus sizeof(arg) should obviously refer to an integer pointer. Building on that, sizeof(&arg) should refer to a pointer to a pointer to an int. To me this looks like were referring a pointer not to the base type which is int. If this is wrong, could you please elaborate a bit? Could you start with what arg in that statement means?Justus
@Pegasus: Stack Overflow comments are a very poor venue to each you basic C even if I had the inclination to do so. You should invest in an elementary tutorial to go through these things. arg here is type int *, therefore &arg is type int ** and *arg is type int. Since you want to allocate space for an int, int * arg = malloc(sizeof(*arg)); is the correct way to do it.Foxtail
@Pegasus: No, it wasn't a typo. I clearly said that int * arg = malloc(sizeof(&arg)); would "allocate space for a pointer to pointer to int", to respond to your mistaken supposition in your preceding comment that int *arg = malloc(sizeof(*arg)); would do that, which it wouldn't. In the actual code, we don't want to allocate space for a pointer to pointer to int - we want to allocate space for an int.Foxtail
yeah thats why I removed my comment but you caught it anyway :). Noevertheless I've got the whole thing now. ThanksJustus
How do I print value of a inside foo?Clove
@NSGodMode: With printf("%d\n", a), since POSIX requires printf() to be thread-safe.Foxtail
In my program I have struct like this : typedef struct { int start; int end; } Range; and i want to print "start" in foo, how do I do this?Clove
@NSGodMode: Then you need to ask a new question, if you have one that doesn't relate to this question.Foxtail
Ok , I'm creating a question now. Please answer it. thanks. I'm doing an assignment due today and I need it for that. ThanksClove
@PaulGriffiths my new question. please answer it : #29739164Clove
B
27

You can allocate an int on the heap and pass it to pthread_create(). You can then deallocate it in your thread function:

void *foo(void *i) {
    int a = *((int *) i);
    free(i);
}

int main() {
    pthread_t thread;
    int *i = malloc(sizeof(*i));
    pthread_create(&thread, 0, foo, (void *) i);
}
Bighead answered 7/10, 2013 at 19:31 Comment(2)
Like I said in another answer : I am not sure this solution work. By the time the first thread reaches int a = *((int *) i), the for loop could have changed the value of i. Thus, when the first thread tries to initialize a, it would not read the right value. Or maybe I am confused with the concept of threads?Accent
@Gradient: Your other comment was correct, but that's not what's happening here. This solution allocates new memory for the argument to each thread (or, at least, if you put it in a loop, you would allocate new memory in each loop) so each thread gets a different object, and no two threads try to access the same memory. You're getting the concept of threads right, this solution just doesn't exhibit the problem you mentioned. I think this solution would be improved by actually showing how it would work in a loop.Foxtail
C
11

You should cast the address of i (rather than the value of i as you do now) in the last argument of pthread_create().

pthread_create(&thread, 0, foo, (void *) &i);
                                         ^  is missing

And the casting is wrong in your function too. It should be:

int a = *((int*) i);
  1. If you intend to read the value, you should also initialize i to some value in main() as it's uninitialized now.

2 Use proper definition for main():

 int main(void) 

or int main(int argc, char *argv[]) or its equivalent.

Calorific answered 7/10, 2013 at 19:35 Comment(7)
Does that work if i is declared in a for loop? For example for (int i=0;...;...) Or should I declared it before the for loop?Accent
Declaring in a for loop is no different & it would work the same way. But declaring variable in for loop is allowed only in C99 (or later) mode. You would need to compile with -std=c99 for example, along with other compiler options.Calorific
Also, if I do &i, then I give the thread the address of variable i. If I create other threads, wouldn't i be shared between all threads? That would not be the desired behavior.Accent
Yes. All threads share the same address space. If sharing is a problem, you have to use locks (e.g mutex) to get exclusive access.Calorific
Ok. I have a for loop that creates threads. Is there a way to pass an integer as the forth argument of pthread_create so that each thread has its own value, independent in each thread? Or maybe I have to create a variable for each thread?Accent
I am not sure the second solution would work. By the time, the first thread reaches int a = *((int *) i), the for loop could have changed the value of i. Thus, when the first thread tries to initialize a, it would not read the right value.Accent
@Gradient: You are correct, passing the address of the loop variable is not guaranteed to be safe. The results of casting an int to a pointer and back are implementation-defined, so this is not a great solution, either. Using malloc() is the best way.Foxtail
R
8

Old question, but I faced the same problem today, and I decided not to follow this path. My application was really about performance, so I chose to have this array of ints declared statically.

Since I don't know a lot of applications where your pthread_join / pthread_cancel is in another scope than your pthread_create, I chose this way :

#define NB_THREADS 4

void *job(void *_i) {
  unsigned int i = *((unsigned int *) _i);
}

int main () {
  unsigned int ints[NB_THREADS];
  pthread_t    threads[NB_THREADS];
  for (unsigned int i = 0; i < NB_THREADS; ++i) {
    ints[i] = i;
    pthread_create(&threads[i], NULL, job, &ints[i]);
  }
}

I find it more elegant, more efficient, and you don't have to worry about freeing since it only lives in this scope.

Radiogram answered 29/7, 2014 at 4:50 Comment(0)
B
4

While this is an old question there is one option missing when all you need is to pass a positive integer like a descriptor: you can pass it directly as the address, while it it a hack it works well and avoid allocating anything :)

NOTE: the size of the integer must match the size of a pointer on your OS but nowadays most systems are native 64bits.

#include <pthread.h>
#include <inttypes.h>
#include <stdio.h>

void *_thread_loop(void *p)
{
  uint64_t n = (uint64_t)p;

  printf("received %llu\n", n);

  return NULL;
}



int main(int argc, char const *argv[])
{
  pthread_t read_thread_id;
  uint64_t n = 42;
  pthread_create(&read_thread_id, NULL, _thread_loop, (void *)n);

  pthread_join(read_thread_id, NULL);
  return 0;
}
Bailor answered 16/1, 2018 at 7:30 Comment(4)
According to this answer, the result of this hack is implementation-defined and (generally speaking) not portable.Affinitive
I am not entirely sure the answer you link really means that, he says the result may not point to any valid data and that is obvious (the pointer will never be dereferenced) but so far I never had issues doing that, I have no tested exotic architectures though but worked for me on linux on x86 and am64 as well as arm (on a raspberrypi).Bailor
Oh, I highly doubt you'll ever have issues with it unless you're running on a really exotic architecture :-) And this hack has worked for me on more than a few occasions. I'm just posting for completeness!Affinitive
is there a way to say "an int of the size of a pointer"? my hope would be to not get any warning on systems where the size isn't a problem and get more significant warnings if the code analysis could identify that my loop index can get bigger than the size of a pointer.Trifolium
S
0

you can intprt_t
Using intptr_t is useful when you need to convert between pointers and integers without loss of information or when you want to ensure that a pointer can be safely converted to an integer type. It's commonly used in scenarios where you need to store a pointer in an integer variable or pass a pointer as an integer argument to a function.

void *foo(void *i) {
    int a = (intptr_t)i;
}

int main() {
    pthread_t thread;
    int i;
    pthread_create(&thread, 0, foo, (void *)(intptr_t)i);  // cast i to intptr_t type
}
Susysuter answered 8/3 at 5:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.