linux thread function Summary

Since the main thread has already begun running, twice the thread still using a serial printer takes a little time, so printing is repeated.

#include "pthread.h"
#include "stdio.h"
#include "stdlib.h"
static void * thread_function(void * arg )
{
 //	printf("%s %d\n ",__FUNCTION__ ,  (int)arg );
	
 	printf("%s %d\n ",__FUNCTION__ ,  *(int*)arg );
	while(1);

	return NULL;
}

int main(int argc, const char *argv[])
{
	pthread_t tid[10];
	int i;
	for(i = 0; i<10 ; i++) {
		//pthread_create(&tid[i] ,NULL, thread_function ,(void *) i );传送值的方法
		pthread_create(&tid[i] ,NULL, thread_function ,(void *) &i ); 传送地址的方法
	}
	while(1)
	{
		//printf("%s\n",__FUNCTION__);
		//sleep(1);
	}
	return 0;
}

  

 

 

 

Command ps -eLf 1 View thread | grep thread;

2 thread is not to create the first implementation is based on the kernel to decide to execute that.

3 can increase the delay in the creation of threads, each thread in order to perform, with such a large log is the order of execution.

 

  Look resources of a process

top -p 4081 

 

 

Thread recovery, pthread_join; just call pthread_exit is not enough, just exit the thread, but the size is not changed.

 pthread_join is a blocking function, so the thread can be changed to pthread_detach changed to detach property is automatically released after the end of the resource.

Thread smaller resources after 20s

#include "pthread.h"
#include "stdio.h"
#include "stdlib.h"
static void * thread_function(void * arg )
{
   printf("%s %d\n ",__FUNCTION__ ,  (int)arg );
    
     //printf("%s %d\n ",__FUNCTION__ ,  *(int*)arg );
    sleep(20);   
    pthread_exit("I quit\n");
    while(1);

    return NULL;
}

int main(int argc, const char *argv[])
{
    pthread_t tid[10];
    int i;
    for(i = 0; i<10 ; i++) {
        pthread_create(&tid[i] ,NULL, thread_function ,(void *) i );
        pthread_detach(tid[i]);
        //pthread_create(&tid[i] ,NULL, thread_function ,(void *) &i );
        //sleep(1);
    
    }

// pthread_join 是阻塞函数,因此可以将线程改为pthread_detach 改为detach属性,
pthread_exit结束后自动释放资源的。
/* int errno ;
for(i = 0; i<10 ; i++)
{
  errno = pthread_join(tid[i] ,NULL);
  if(errno == -1 )
  {
    perror("pthread_exit"); return -1 ;
  }
}
*/

  while(1)
  {
//printf("%s\n",__FUNCTION__); //sleep(1);
  }

  return 0;
}

 

 

Guess you like

Origin www.cnblogs.com/jack-hzm/p/11372276.html