小白初识linux下的C语言多线程

168 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路

linux多线程的初步了解

欢迎

下面举例 :创建52个线程

一个教授,一个助教,50个学生

#include <unistd.h>     /* Symbolic Constants */
#include <sys/types.h>  /* Primitive System Data Types */ 
#include <errno.h>      /* Errors */
#include <stdio.h>      /* Input/Output */
#include <stdlib.h>     /* General Utilities */
#include <pthread.h>    /* POSIX Threads */
#include <string.h>     /* String handling */
#include <time.h>

/* prototype for thread routine */
void print_message_function ( void *ptr );

/* struct to hold data to be passed to a thread
   this shows how multiple data items can be passed to a thread */
typedef struct str_thdata
{
    int  thread_no;
    char message[100];
}thdata;

int main()
{
    pthread_t thread[52];  /* thread variables */
    thdata data[52];         /* structs to be passed to threads */
    
    /* initialize data to pass to thread 1 */
    data[0].thread_no = 1;
    strcpy(data[0].message, "TY doctor!");

    /* initialize data to pass to thread 2 */
    data[1].thread_no = 2;
    strcpy(data[1].message, "yang teaching assistant!");
    
    /* initialize data to pass to thread 3-52 */
    for(int i=2;i<52;i++){
		data[i].thread_no = i+1;
		strcpy(data[i].message,"student");
    }
    
    srand((int)time(NULL));
    /* create threads 1 and 2 */    
    pthread_create (&thread[0], NULL, (void *) &print_message_function, (void *) &data[0]);
    usleep(1);
    pthread_create (&thread[1], NULL, (void *) &print_message_function, (void *) &data[1]);
	usleep(1);
	for(int i=2;i<52;i++){
		pthread_create (&thread[i], NULL, (void *) &print_message_function, (void *) &data[i]);
		int m=rand()%200;
		usleep(m);
	}
	
	
    /* Main block now waits for all threads to terminate, before it exits
       If main block exits, both threads exit, even if the threads have not
       finished their work */ 
    for(int j=0;j<52;j++)
    	pthread_join(thread[j], NULL);

    /* exit */  
    exit(0);
} /* main() */

/**
 * print_message_function is used as the start routine for the threads used
 * it accepts a void pointer 
**/
void print_message_function ( void *ptr )
{
    thdata *data;            
    data = (thdata *) ptr;  /* type cast to a pointer to thdata */
    
    /* do the work */
    if(data->thread_no>2){
    	printf("Thread %2d says %s %2d\n", data->thread_no, data->message,(data->thread_no-2));
    }
    else{
        printf("Thread %2d says %s \n", data->thread_no, data->message);
    }
    
    pthread_exit(0); /* exit */
} /* print_message_function ( void *ptr ) */

输出样例

$ gcc -o main main.c -lpthread
$ ./main
Thread  1 says doctor! 
Thread  2 says teaching assistant! 
Thread  3 says student  1
Thread  4 says student  2
Thread  5 says student  3
......
Thread 51 says student 49
Thread 52 says student 50