There is a pthread_create() function, the template of which looks like this:
int pthread_create(pthread_t *pth, pthread_attr_t *att, void * (*function)(void *), void *arg); And I have some questions about this feature:
1) The function call in different sources looks different, which one is correct and is there any difference at all?
void * fun(void *arg){ int count = * (int *)arg; printf("Thread %d\n", count); pthread_exit(NULL); } int main(void) { pthread_t thread; int count = 1; pthread_create(&thread, NULL, fun, &count); // первый способ pthread_create(&thread, NULL, &fun, &count); // второй способ pthread_exit(NULL); } 2) Why, when we pass the function fun() pthread_create() function, we don’t pass any argument to it? Instead, I read somewhere that the fourth argument of the pthread_create() function is passed to the fun() function, but I don’t understand how this is done
3) The pthread_create() ) function first takes a pointer to pthread_t * , is this done to save memory, etc., or because the address plays a role? Just the code below proves that the address does not matter:
void * fun(void *arg){ int count = * (int *)arg; printf("Thread %d\n", count); pthread_exit(NULL); } int main(void) { int i = 0; int *status; while(i < 10){ pthread_t thread; status = malloc(1); *status = i++; pthread_create(&thread, NULL, fun, (void *)status); printf("%ld\n", thread); } Here 10 threads are created, and the address of the thread does not change.
funand&fun(in this case there is no difference). Callingfunsomewhere insideint pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg)already in the new thread is written like this:start_routine(arg);- avpmallocshould not be called from 1, but fromsizeof(int)(yes, in standard implementations in both cases, enough memory will be allocated (most likely 16 (maybe 8) bytes) ) - avp