Re: (no subject)



>threads stuff. The "working" thread (THR) does start when START is
>clicked, but then STOP does not respond, and THR keeps running. This is my
>first example using threads with gtk, and there are many thing that I
>don't understand. 

pthread_cancel() only has an effect when a thread encounters a
"cancellation point". for example, if it was executing:

	      while (1);

pthread_cancel() would have no effect whatosever. And hey, what do you
know ?

>// Function executed by THR
>void work(void * arg)
>{
>    int i;
>
>    // Some CPU intensive task
>    for(i=0; i<100000; i++)
>	printf("%d\n", i);
>
>}

Not much different. I might have guessed that printf(3) encountered a
cancellation point along its execution path, but perhaps not.

You can't expect pthread_cancel() to work the way that kill(2) works
on processes. If you need to stop one thread from another thread, in
the general case you need to have the first thread check if it should
stop, as in:

int stop = 0;
pthread_t thread;

void *
thread_function (void *arg)
{
      int status;

      for (i = 0; i < LIMIT && !stop; i++) {
            ... do something ...
      }
      
      status = (i == LIMIT);
      return &status;
}

void
start_thread ()

{
	pthread_create (&thread, ..., thread_function, ...);
}

void
stop_thread ()

{
	void *status;
	stop = true;
	/* now wait till the thread has exited */
	pthread_join (thread, &status);
	printf ("thread exited with status %d\n", *((int *) status));
}

BTW, the prototype of your thread function is wrong. thread functions
return "void *", expected to be a pointer to some status variable of
some kind. In my example, its not completely safe either, since status
lives on the stack, but thats a detail left for you to clean up.

--p





[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]