Dave's Brain

Browse - Programming Tips - How can I pass an enum by value to a thread?

Date: 2015sep23
Language: C/C++

Q.  How can I pass an enum by value to a thread?

A.  If you are passing a small value (like an enum)
you don't need to malloc() etc.  Here is an example.

#include <unistd.h> // For sleep() #include <stdio.h> // For printf() #include <pthread.h> #include <stdint.h> // For intptr_t typedef enum { ONE = 1111, TWO = 2222, THREE = 3333 } MyEnum; static void *threadMain(void *pParam) { // Casting to intptr_t is make it clear what you are doing MyEnum param = (MyEnum) (intptr_t) pParam; printf("Thread received %d\n", param); return NULL; } int main(int argc, char *argv[]) { pthread_t handle; pthread_create(&handle, NULL, threadMain, (void *) THREE); // Stay alive long enough for the thread to do its work sleep(10); }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.