Linux multi-threading and mutex programming instance __ block chain

Source: Internet
Author: User
Tags function prototype mutex

This article go from:
http://www.cnblogs.com/armlinux/archive/2010/05/28/2396997.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: The main function is 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: The main function is waiting for me to complete the task."
        /n ");
Pthread_exit (NULL); } VOID thread_create (void) {int temp;          memset (&thread, 0, sizeof (thread));     
                COMMENT1/* Create thread */if (temp = pthread_create (&thread[0), NULL, THREAD1, NULL)!= 0)//comment2
        printf ("Thread 1 Create failed!/n");

        else printf ("Thread 1 is created/n");
        if (temp = Pthread_create (&thread[1], NULL, THREAD2, NULL)!= 0)//comment3 printf ("Thread 2 creation failed");
else printf ("Thread 2 is created/n");    
                } void thread_wait (void) {/* Wait thread end/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");

        the int main () {/* is used to initialize the mutex/Pthread_mutex_init (&mut,null) with default attributes;
        printf ("I'm the main function oh, I'm creating threads, hehe/n"); Thread_create();
        printf ("I'm the main function oh, I'm waiting for the thread to finish the task, hehe/n");

        Thread_wait ();
return 0; }

Let's start by compiling and executing

Citation:

falcon@falcon:~/program/c/code/ftp$ gcc-lpthread-o thread_example thread_example.c
falcon@falcon:~/program/c/ code/ftp$./thread_example
I'm the main function oh, I'm creating a thread, hehe
thread 1 was created
thread 2 was created I'm the
main function Oh, I'm waiting for the thread to complete the task Ah, hehe
thread1: I ' m thread 1
thread1:number = 0
thread2:i ' m thread 2
thread2:number = 1
thread1:number = 2
th Read2:number = 3
thread1:number = 4
thread2:number = 5
thread1:number = 6
thread1:number = 7
Thread2:number = 8
thread1:number = 9
thread2:number = ten
thread1: The main function is waiting for me to finish the task.
thread 1 has ended
thread2: The main function is waiting for me to finish the task.
Thread 2 has ended

The comments in the instance code should be more clear, and I'll refer to some of the functions and variables mentioned above on the Internet. thread-related actions First, pthread_t

pthread_t is defined in the header file/usr/include/bits/pthreadtypes.h:
typedef unsigned long int pthread_t;
It is an identifier for a thread. Second, Pthread_create

function pthread_create is used to create a thread whose prototype is:

extern int pthread_create __p (pthread_t *__thread, __const pthread_attr_t *__attr,  void * (*__start_routine) (void * ), void *__arg);

The first argument is a pointer to the thread identifier
The second parameter is used to set the thread properties
The third parameter is the starting address of the thread run function
The last parameter is the parameter of the running function.
Here, our function thread does not require arguments, so the last argument is set to a null pointer. The second argument is also set to a null pointer, which will generate the thread for the default property. Set up and modify the thread properties we'll explain in the next section. When the line Cheng is created, the function returns 0, if not 0, the creation thread fails, and the common error return code is eagain and einval. The former indicates a system restriction to create a new thread, such as an excessive number of threads, which indicates that the second parameter represents an illegal thread property value. After the creation of the thread succeeds, the newly created thread runs the function of parameter three and parameter four, and the original thread continues to run the next line of code. third, Pthread_join pthread_exit

  
function Pthread_join is used to wait for the end of a thread. The function prototype is:


extern int Pthread_join __p ((pthread_t __th, void **__thread_return));
  
The first parameter is the waiting thread identifier
The second parameter is a user-defined pointer that can be used to store the return value of the waiting thread.
This function is a thread-blocking function, and the function that calls it waits until the thread that is waiting is finished, and when the function returns, the resource of the waiting thread is retracted . There are two ways to end a thread, like the example above, when the function ends, and the thread that calls it ends.

Another way is to implement it through function pthread_exit. Its function prototype is:
  
extern void Pthread_exit __p ((void *__retval)) __attribute__ ((__noreturn__));
  
The only parameter is the return code of the function, and the value is passed to Thread_return as long as the second argument in the Pthread_join Thread_return is not null. Finally, one thread cannot be waited by multiple threads, otherwise the first line that receives the signal Cheng returned, and the rest of the Pthread_join thread returns the error code esrch.
In this section, we have written one of the simplest threads and mastered the most commonly used three functions pthread_create,pthread_join and pthread_exit. Let's look at some of the common properties of threads and how to set these properties. Mutual exclusion Lock related

Mutexes are used to ensure that only one thread executes a piece of code over a period of time. First, Pthread_mutex_init

Prototype:
int pthread_mutex_init (pthread_mutex_t  *restrict Mutex,  const pthread_mutexattr_t  *restrict attr);
Instance:
/* Initialize mutex
/pthread_mutex_init (&mut,null) with default attributes;

function pthread_mutex_init is used to generate a mutual exclusion lock. The null parameter indicates that the default property is used. If you need to declare a mutex for a particular attribute, you must call the function Pthread_mutexattr_init.

function pthread_mutexattr_setpshared and function Pthread_mutexattr_settype are used to set mutex properties.
The previous function sets the property pshared, which has two values: Pthread_process_private pthread_process_shared

The former is used to synchronize threads in different processes, which are used to synchronize different threads of this process. In the example above, we are using the default property Pthread_process_ PRIVATE. The latter is used to set the mutex type, and the optional types are pthread_mutex_normal, Pthread_mutex_errorcheck, pthread_mutex_recursive, and PTHREAD _mutex_ DEFAULT. They define different mechanisms of the upper and the unlocked, and generally choose the last default attribute. Ii. Pthread_mutex_lock, Pthread_mutex_unlock and pthread_delay_np

The Pthread_mutex_lock declaration begins with a mutex lock, and the following code is locked until the call to Pthread_mutex_unlock, which can only be executed by one thread at a time . When a thread executes to pthread_mutex_lock, if the lock is used by another thread at this time, the thread is blocked, which means that the program waits to another thread to release the mutex.

Note:

1, it is necessary to note that the above two sleep is not only for the demonstration of the need, but also in order to let the thread for a while, let the thread release the mutex, waiting for another thread to use the lock. The issue is illustrated in reference 1 below. But there seems to be no pthread_delay_np for that function (I tried it, the hint doesn't define a reference to the function), so I used sleep instead, but in reference 2 there's another way, as if by Pthread_cond_ Timedwait to replace it, it gives a way to achieve it.

2, please be sure to pay attention to the comments inside the comment1-5, it is the problem that I spent a few hours to find out.
If there are no comment1 and comment4,comment5, it will cause a segment error in Pthread_join, and the above Comment2 and comment3 are the root cause, so remember to write all the code. Because the thread above may not have been created successfully, it is impossible to wait until that thread ends, and there is a segment error (Accessing the unknown memory area) when using Pthread_join. In addition, when using memset, you need to include the string.h header file, oh

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.