Pthread memória zabálás

Fórumok

Kelle egy egyszerű threadet csinálnom, találtam hozzá egy még egyszerűbb teszt programot, amit kibővíttettem, hogy kb 5000-szer nyisson csukjon egy thread-et, a probléma az hogy folyamatosan eszi a memóriát (már a 10 -nél 100 Mb) és csak nő nő nő.
Mi lehet a probléma ??


A példa :

#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <syslog.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>

#include <pthread.h>
//#include <stdio.h>
#define NUM_THREADS     5000

void *PrintHello(void *threadid)
{
   printf("\n%d: Hello World!\n", threadid);
      pthread_exit(NULL);
}
      
int main (int argc, char *argv[])
{
     pthread_t threads[NUM_THREADS];
     int rc, t;
     for(t=0; t<NUM_THREADS; t++){
         printf("Creating thread %d\n", t);
         rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
         if (rc){
          printf("ERROR; return code from pthread_create() is %d\n", rc);
          exit(-1);
         }
	 sleep(1);
     }
     pthread_exit(NULL);
} 

Hozzászólások

Egyszer én is belefutottam ebbe :) A megoldás egyébként valamelyk pthread függvény kézikönyvéban van :
Ha "Joinable" thread-t hozol létre (ez az alapértelmezett talán?) akkor a thread létrehozása után szükséges egy pthread_join is, különben memória szivárgás lép fel. Vagy megadod a thread attribútumai között, hogy ez nem "Joinable" és így hozod létre az új szálat, de akkor talán nem tudod kilőni a szálat pthread_kill-el.

Köszi. Megoldódott, tényleg az attributum volta a kulcs.
Mások számára itt a helyes megoldás



include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <syslog.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>

#include <pthread.h>
//#include <stdio.h>
#define NUM_THREADS     50000

void *PrintHello(void *threadid)
{
   printf("\n%d: Hello World!\n", threadid);
      pthread_exit(NULL);
}



int main (int argc, char *argv[])
{
    pthread_attr_t attr;

    pthread_attr_init(&attr);
    if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)!=0) { printf("hiba\n"); exit(-1); }

     pthread_t threads[NUM_THREADS];
     int rc, t;
     for(t=0; t<NUM_THREADS; t++){
         printf("Creating thread %d\n", t);
         rc = pthread_create(&threads[t], &attr, PrintHello, (void *)t);
         if (rc){
          printf("ERROR; return code from pthread_create() is %d\n", rc);
          exit(-1);
         }
//       sleep(1);
     }
     sleep(100);
     pthread_attr_destroy(&attr);
     pthread_exit(NULL);
}