LINUX.ORG.RU

pthread


0

0

Тестовая програмка вываливаеться через секунд тридцать. Что я делаю не так. (Каптча -> stoped)

#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include "string.h"

#define STR "Test\n" void *print_message_function( void *ptr );

main() { pthread_t thread; int iret; int i = 0; for (;;){

iret = pthread_create( &thread, NULL, print_message_function, (void*)i); printf("Thread 1 returns: %d\n",iret); usleep(1500); pthread_cancel(thread); i = i++; }

exit(0); }

void *print_message_function( void *ptr ) { int num = (int) ptr; int i = 0; for (;;){ write(1, STR, strlen(STR)); i ++; } }

anonymous

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "string.h"

#define STR	"Test\n"
void *print_message_function( void *ptr );

main()
{
     pthread_t thread;
     int  iret;
     int i = 0;
     for (;;){

       iret = pthread_create( &thread, NULL, print_message_function, (void*)i);
       printf("Thread 1 returns: %d\n",iret);
       usleep(1500);
       pthread_cancel(thread); 
       i = i++;
     }

     exit(0);
}

void *print_message_function( void *ptr )
{
     int num = (int) ptr;
     int i = 0;
     for (;;){ 
        write(1, STR, strlen(STR)); 
        i ++;
     }
        
}

anonymous
()
Ответ на: комментарий от tailgunner

2tailgunner:

Поставь и отпишись. copy -> paste gcc test.c -o test -lpthread

anonymous
()
Ответ на: комментарий от T-34

2T-34:

Может какой нибудь толковый форум по линуксу подскажешь? А то брат приезжает и я месяца два должен пить.

anonymous
()
Ответ на: комментарий от anonymous

Читайте, Великие Воины Красноглазия! Какой позор...

http://www.lambdacs.com/cpt/FAQ.html

Q16: After 1800 calls to thr_create() the system freezes. ??

My problem is that the thread does not get freed or released back to the system for reuse. After 1800 calls to thr_create() the system freezes. ?? A: The default for threads in both UI and POSIX is for threads to be "undetached" -- meaning that they MUST be joined (thr_join()). Otherwise they will not be garbage collected. (This default is the wrong choice. Oh well.)

anonymous
()
Ответ на: комментарий от anonymous

Вроде все работает, какая у вас версия ядра, gcc, libc? Зачем нужна строка: #include "string.h" ?

Может нужно проверять результаты вызовов pthread_create() и pthread_cancel()...

mky ★★★★★
()
Ответ на: комментарий от mky

2mky:

Да это ещо два года назад было. Тогда я посмотрел исходники gimp и сделал всё через g_add_idlle_function()(что то наподобии). Gcc и libc у меня всё что стоит в Ubuntu, обновляюсь своевременно. Кстати из этого же faq.

Q324: Cancelling detached threads (posix threads)?

Jason Nye wrote:

> I'm trying to find out whether the posix specification allows the > cancellation of detached threads. I have a copy of Butenhof's book and in > the posix mini-reference at the end of the book, he says that pthread_cancel > should fail if the target thread is detached. This makes sense to me, but is > this the correct behaviour? For example LinuxThreads does allow cancellation > of a detached thread -- who is correct?

This is actually an ambiguity in the standard. An implementation that allows cancellation of a detached thread doesn't violate the standard. HOWEVER, other provisions of the standard make such an allowance of questionable value, at best. For example, when a detached thread terminates the state of that thread is immediately invalidated, and may be reused immediately for a new thread. At that point (which you cannot determine) you would be cancelling some new thread that you probably didn't create, with possibly disastrous consequences to your application.

There's no excuse for ever cancelling a detached thread. If you do, you may be breaking your application. If it works today, it might not work tomorrow, for reasons you cannot easily determine.

In other words, regardless of what the standard says, this is an application error that individual implementations may or may not detect. (And in the general case, implementations that reuse pthread_t values cannot detect the cases where it really matters, because when you cancel a reused pthread_t, the value is valid at the time.)

So, if you believe my interpretation, you're less likely to get yourself into trouble by taking advantage of dangerous (and in the final analysis, unusable) loopholes provided by other implementors. ;-)

anonymous
()
Ответ на: комментарий от anonymous

Вот так всё работает:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>


void *print_message_function( void *ptr );

main()
{
     pthread_t thread;
     pthread_attr_t attr;
     int  iret;
     int i = 0;
     pthread_attr_init(&attr);
     pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
     for (;;){

       iret = pthread_create( &thread, &attr, print_message_function, (void*)i);
       printf("Thread 1 returns: %d\n",iret);
       usleep(500);
       pthread_cancel(thread); 
       i = i++;
     }

     pthread_attr_destroy(&attr); // ;)
     exit(0);
}

void *print_message_function( void *ptr )
{
     int num = (int) ptr;
     int i = 0;
     for (;;){ 
        pthread_testcancel();
        printf("%s %d %d\n", "Thread : ", num, i); 
        i ++;
     }
        
}

anonymous
()
Ответ на: комментарий от anonymous

i = i++; // ;)

закройте пожалуйста эту тему.

anonymous
()
Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.