Simply put, a process copies a piece of code into multiple copies and allows them to execute them simultaneously. Inter-process communication aims to make them run in an orderly manner.
In short, threads allow multiple functions to be executed at the same time, and inter-thread communication aims to make them run in an orderly manner.
When compiling a thread program, a warning is reported that the thread function cannot be found.
The pthread library is not the default library of the Linux system. You must use the static library libpthread. A during connection. Therefore, you must use pthread_create () to create a thread and call
When the pthread_atfork () function creates a fork handler, You need to link this library.
Solution:
Add the-lpthread parameter to the compilation.
GCC thread. C-o thread-lpthread
Thread. C is your source file. Do not forget to add the header file # include <pthread. h>
Http://blog.csdn.net/llqkk/article/details/2854558
Instance 1: create two threads and execute the same function at the same time
/* Ex7-1.c */
# Include <stddef. h>
# Include <stdio. h>
# Include <unistd. h>
# Include <pthread. h>
# Include <string. h>
Void print_msg (char * PTR );
Int main ()
{
Pthread_t thread1, thread2;
Int I, J;
Char * msg1 = "Do sth1 \ n ";
Char * msg2 = "Do sth2 \ n ";
Pthread_create (& thread1, null, (void *) (& print_msg), (void *) msg1 );
Pthread_create (& thread2, null, (void *) (& print_msg), (void *) msg2 );
Sleep (1 );
Return 0;
}
Void print_msg (char * PTR)
{
Int retval;
Int id = pthread_self ();
Printf ("thread ID: % x \ n", ID );
Printf ("% s", PTR );
Pthread_exit (& retval );
}
Execute GCC ex7-1.c-lpthread
./A. Out
Instance 2 creates multiple threads to execute different functions
Code from http://www.cnblogs.com/BiffoLee/archive/2011/11/18/2254540.html
# Include <pthread. h>
# Include <stdio. h>
# Include <sys/time. h>
# Include <string. h>
# Define max 10
Pthread_t thread [2];
Pthread_mutex_t mut;
Int number = 0, I;
Void * thread1 ()
{
Printf ("thread1: I'm thread 1 \ n ");
For (I = 0; I <Max; I ++)
{
Printf ("thread1: Number = % d \ n", number );
Pthread_mutex_lock (& MUT );
Number ++;
Pthread_mutex_unlock (& MUT );
Sleep (2 );
}
Printf ("thread1: is the main function waiting for me to complete the task? \ N ");
Pthread_exit (null );
}
Void * thread2 ()
{
Printf ("thread2: I'm thread 2 \ n ");
For (I = 0; I <Max; I ++)
{
Printf ("thread2: Number = % d \ n", number );
Pthread_mutex_lock (& MUT );
Number ++;
Pthread_mutex_unlock (& MUT );
Sleep (3 );
}
Printf ("thread2: is the main function waiting for me to complete the task? \ N ");
Pthread_exit (null );
}
Void thread_create (void)
{
Int temp;
Memset (& Thread, 0, sizeof (thread); // comment1
// Create a thread
If (temp = pthread_create (& Thread [0], null, thread1, null ))! = 0) // comment2
Printf ("thread 1 creation failed! \ N ");
Else
Printf ("thread 1 created \ n ");
If (temp = pthread_create (& Thread [1], null, thread2, null ))! = 0) // comment3
Printf ("thread 2 creation failed ");
Else
Printf ("thread 2 created \ n ");
}
Void thread_wait (void)
{
// Wait until the thread ends
If (thread [0]! = 0) {// comment4
Pthread_join (thread [0], null );
Printf ("thread 1 has ended \ n ");
}
If (thread [1]! = 0) {// comment5
Pthread_join (thread [1], null );
Printf ("thread 2 has ended \ n ");
}
}
Int main ()
{
// Use the default attribute to initialize the mutex lock
Pthread_mutex_init (& Mut, null );
Printf ("I am the main function, I am creating a thread, haha \ n ");
Thread_create ();
Printf ("I am the main function, I am waiting for the thread to complete the task, haha \ n ");
Thread_wait ();
Return 0;
}
?
Compile:
Gcc-lpthread-O thread_example LP. c
Example 3: semaphore control thread running sequence
/* Thread_sem.c */
# Include <stdio. h>
# Include <stdlib. h>
# Include <pthread. h>
# Include <semaphore. h>
# Define thread_number 3
# Define repeat_number 3
# Define delay_time_levels 10.0
Sem_t SEM [thread_number];
Void * thrd_func (void * Arg)
{
Int thrd_num = (INT) ARG;
Int delay_time = 0;
Int COUNT = 0;
Sem_wait (& SEM [thrd_num]);
Printf ("thread % d is starting \ n", thrd_num );
For (COUNT = 0; count <repeat_number; count ++)
{
Delay_time = (INT) (RAND () * delay_time_levels/(rand_max) + 1;
Sleep (delay_time );
Printf ("\ tthread % d: Job % d delay = % d \ n", thrd_num, Count, delay_time );
}
Printf ("thread % d finished \ n", thrd_num );
Pthread_exit (null );
}
Int main (void)
{
Pthread_t thread [thread_number];
Int NO = 0, Res;
Void * thrd_ret;
Srand (Time (null ));
For (NO = 0; no <thread_number; no ++)
{
Sem_init (& SEM [No], 0, 0 );
Res = pthread_create (& Thread [No], null, thrd_func, (void *) No );
If (res! = 0)
{
Printf ("create thread % d failed \ n", no );
Exit (RES );
}
}
Printf ("create treads success \ n waiting for threads to finish... \ n ");
Sem_post (& SEM [thread_number-1]);
For (NO = thread_number-1; no> = 0; no --)
{
Res = pthread_join (thread [No], & thrd_ret );
If (! Res)
{
Printf ("thread % d joined \ n", no );
}
Else
{
Printf ("thread % d join failed \ n", no );
}
Sem_post (& SEM [(NO + thread_number-1) % thread_number]);
}
For (NO = 0; no <thread_number; no ++)
{
Sem_destroy (& SEM [No]);
}
Return 0;
}
Instance 4: Use of mutex lock
In this program, one thread needs to write data to the buffer, and the other thread needs to read data, so only one thread can operate on the buffer at a time.
/* Ex7-3.c */
# Include <stddef. h>
# Include <stdio. h>
# Include <unistd. h>
# Include <pthread. h>
# Define false 0
# Define true 1
Void readfun ();
Void writefun ();
Char buffer [256];
Int buffer_has_item = 0;
Int retflag = false, I = 0;
Pthread_mutex_t mutex;
Int main ()
{
Void * retval;
Pthread_t reader;
Pthread_mutex_init (& mutex, null );
Pthread_create (& reader, null, (void *) & readfun, null );
Writefun ();
Pthread_join (reader, & retval );
}
Void readfun ()
{
While (1)
{
If (retflag)
Return;
Pthread_mutex_lock (& mutex );
If (buffer_has_item = 1)
{
Printf ("% s", buffer );
Buffer_has_item = 0;
}
Pthread_mutex_unlock (& mutex );
}
}
Void writefun ()
{
Int I = 0;
While (1)
{
If (I = 10)
{
Retflag = true;
Return;
}
Pthread_mutex_lock (& mutex );
If (buffer_has_item = 0)
{
Sprintf (buffer, "this is % d \ n", I ++ );
Buffer_has_item = 1;
}
Pthread_mutex_unlock (& mutex );
}
}
Instance 5 condition Variables
Text
/* ex7-4.c */#include <stdio.h>#include <pthread.h>#define BUFFER_SIZE 4#define OVER (-1)struct producers{int buffer[BUFFER_SIZE];pthread_mutex_tlock;intreadpos, writepos;pthread_cond_tnotempty;pthread_cond_tnotfull;};void init(struct producers *b){pthread_mutex_init(&b->lock,NULL);pthread_cond_init(&b->notempty,NULL);pthread_cond_init(&b->notfull,NULL);b->readpos=0;b->writepos=0;}void put(struct producers *b, int data){pthread_mutex_lock(&b->lock);while((b->writepos+1)%BUFFER_SIZE==b->readpos){pthread_cond_wait(&b->notfull,&b->lock);}b->buffer[b->writepos]=data;b->writepos++;if(b->writepos>=BUFFER_SIZE) b->writepos=0;pthread_cond_signal(&b->notempty);pthread_mutex_unlock(&b->lock);}int get(struct producers *b){int data;pthread_mutex_lock(&b->lock);while(b->writepos==b->readpos){pthread_cond_wait(&b->notempty,&b->lock);}data=b->buffer[b->readpos];b->readpos++;if(b->readpos>=BUFFER_SIZE) b->readpos=0;pthread_cond_signal(&b->notfull);pthread_mutex_unlock(&b->lock);return data;}struct producers buffer;void *producer(void *data){int n;for(n=0;n<10;n++){printf("Producer : %d-->\n",n);put(&buffer,n);}put(&buffer,OVER);return NULL;}void *consumer(void *data){int d;while(1){d=get(&buffer);if(d==OVER) break;printf("Consumer: --> %d\n",d);}return NULL;}int main(){pthread_t tha,thb;void *retval;init(&buffer);pthread_create(&tha,NULL,producer,0);pthread_create(&thb,NULL,consumer,0);pthread_join(tha,&retval);pthread_join(thb,&retval);return 0;}