Pass integer value through pthread_create

I just want to pass the integer value to the stream.

How can i do this?

I tried:

int i; pthread_t thread_tid[10]; for(i=0; i<10; i++) { pthread_create(&thread_tid[i], NULL, collector, i); } 

The flow method is as follows:

  void *collector( void *arg) { int a = (int) arg; ... 

I get the following warning:

  warning: cast from pointer to integer of different size [-Wpointer-to-int-cast] 
+6
source share
4 answers

The compiler will complain if you don't draw i on the void pointer:

 pthread_create(&thread_tid[i], NULL, collector, (void*)i); 

However, casting an integer to a pointer is not strictly safe:

ISO / IEC 9899: 201x 6.3.2.3 Indices

  1. An integer can be converted to any type of pointer. Except, as indicated earlier, the result is determined by the implementation, may not be aligned correctly, may not point to an object of a reference type, and may be a trap representation.

so you better pass a separate pointer to each thread.

Here's a complete working example that passes each thread a pointer to a single element in an array:

 #include <pthread.h> #include <stdio.h> void * collector(void* arg) { int* a = (int*)arg; printf("%d\n", *a); return NULL; } int main() { int i, id[10]; pthread_t thread_tid[10]; for(i = 0; i < 10; i++) { id[i] = i; pthread_create(&thread_tid[i], NULL, collector, (void*)(id + i)); } for(i = 0; i < 10; i++) { pthread_join(thread_tid[i], NULL); } return 0; } 

There is a nice introduction to pthreads here .

+6
source
 void *foo(void *i) { int a = *((int *) i); free(i); } int main { int *arg = (char*)malloc(sizeof(char)) pthread_create(&thread, 0, foo, arg); } 
+1
source

int is 32 bits, and void * is 64-bit on 64-bit Linux; In this case, you should use long int instead of int;

 long int i; pthread_create(&thread_id, NULL, fun, (void*)i); 

int fun (void * i) function

  long int id = (long int) i; 
0
source

It is better to use struct to send more parameters to one:

 struct PARAMS { int i; char c[255]; float f; } params; pthread_create(&thread_id, NULL, fun, (void*)(&params)); 

then you can cast params to PARAMS* and use it in the pthread routine :

 PARAMS *p = static_cast<PARAMS*>(params); p->i = 5; strcpy(p->c, "hello"); p->f = 45.2; 
0
source

Source: https://habr.com/ru/post/956769/


All Articles