Advertisement
Guest User

iup_pthread.c

a guest
Dec 28th, 2018
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.16 KB | None | 0 0
  1. /**************************************************************************************************
  2.  * IUP program that runs a "long" function in a second thread when the user clicks the button.    *
  3.  * cc iup_pthread.c -o iup_pthread -W -pedantic -ansi -std=c99 -I/usr/include/iup -liup -lpthread *
  4.  **************************************************************************************************/
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <unistd.h>
  8. #include <pthread.h>
  9. #include <iup.h>
  10.  
  11. pthread_t thread1;
  12. int  iret1;
  13.  
  14. void *worker_function( void *ptr )
  15. {
  16.     /**************************************************************************************
  17.      * Do not call IUP functions from other threads as IUP 3 is currently not thread-safe *
  18.      **************************************************************************************/
  19.     for (int i = 0; i < 100; i++) {
  20.         sleep(5);
  21.         printf("%s \n", "worker function");
  22.     }
  23.     return NULL;
  24. }
  25.  
  26. int btn_cb( Ihandle *self )
  27. {
  28.     /************************************************************************************
  29.      * Do not use variables created on the callback function as they will lose context  *
  30.      * as soon as the callback function reach the return point.                         *
  31.      * Use global variables instead if you need to pass arguments to the second thread. *
  32.      ************************************************************************************/
  33.     iret1 = pthread_create( &thread1, NULL, worker_function, NULL);
  34.     pthread_detach(thread1);
  35.     return IUP_DEFAULT;
  36. }
  37.  
  38. int main(int argc, char **argv)
  39. {
  40.   Ihandle *dlg, *button, *label, *vbox;
  41.  
  42.   IupOpen(&argc, &argv);
  43.  
  44.   label =  IupLabel("Start second thread:");
  45.   button = IupButton("Start", NULL);
  46.   vbox = IupVbox(
  47.     label,
  48.     button,
  49.     NULL);
  50.   IupSetAttribute(vbox, "ALIGNMENT", "ACENTER");
  51.   IupSetAttribute(vbox, "GAP", "10");
  52.   IupSetAttribute(vbox, "MARGIN", "10x10");
  53.  
  54.   dlg = IupDialog(vbox);
  55.   IupSetAttribute(dlg, "TITLE", "pthread test");
  56.  
  57.   /* Registers callbacks */
  58.   IupSetCallback(button, "ACTION", (Icallback) btn_cb);
  59.  
  60.   IupShowXY(dlg, IUP_CENTER, IUP_CENTER);
  61.  
  62.   IupMainLoop();
  63.  
  64.   IupClose();
  65.   return EXIT_SUCCESS;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement