Linux C multithreaded programming

Source: Internet
Author: User

Learning things, often examples are the most interesting, always learn the basic theory, do not hands, feel no sense of accomplishment, hehe.

Let's start with an example. We implement the sliding scale of a number by creating two threads.
Perhaps this example has no practical value, but a little change, we can use other places to pull.

Here's our code:

/*THREAD_EXAMPLE.C:C multiple thread programming in Linux *author:falcon *e-mail: [email protected] */#inclu De <pthread.h> #include <stdio.h> #include <sys/time.h> #include <string.h> #define MAX        10pthread_t thread[2];p thread_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 finish 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 finish 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 creation 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 for thread to end */if (thread[0]!=0)
           {             //comment4    
                Pthread_join (thread[0],null);                printf ("Thread 1 has ended/n");          }        
           {  
                Comment5
               Pthread_join (thread[1],null);                printf ("Thread 2 has ended/n");}         } int main () {/        * Initializes the mutex with default properties *        /Pthread_mutex_init (&mut,null);        printf ("I am the main function Oh, I am creating threads, hehe/n");        Thread_create ();        printf ("I am the main function, oh, I am waiting for the thread to finish the task, AH/n");        Thread_wait ();        return 0;}

Let's start by compiling and executing

Citation:


[Email protected]:~/program/c/code/ftp$ gcc-lpthread-o thread_example thread_example.c
[Email protected]:~/program/c/code/ftp$./thread_example
I am the main function Oh, I am creating threads, hehe
Thread 1 is created
Thread 2 is created
I am the main function oh, I am waiting for the thread to finish the task Ah, hehe
Thread1:i ' m thread 1
Thread1:number = 0
Thread2:i ' m thread 2
Thread2:number = 1
Thread1:number = 2
Thread2:number = 3
Thread1:number = 4
Thread2:number = 5
Thread1:number = 6
Thread1:number = 7
Thread2:number = 8
Thread1:number = 9
Thread2:number = 10
THREAD1: is the main function waiting for me to finish the task?
Thread 1 has ended
THREAD2: is the main function waiting for me to finish the task?
Thread 2 has ended




The comments in the instance code should be clearer, and I'll refer to the following functions and variables on the Internet.

Citation:


Thread-related operations

A pthread_t

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

Two int Pthread_create (pthread_t *, attribute *,void*, parameter of function *);

The 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 sets the Thread property, the third argument is the starting address of the thread's running function, and the last parameter is the argument that runs the function. Here, our function thread does not require arguments, so the last parameter is set to a null pointer. The second parameter we also set as a null pointer, which will generate the default properties of the thread. The setting and modification of thread properties is described in the next section. When creating a line Cheng, the function returns 0, if not 0, the creation thread fails, the common error return codes are Eagain and einval. The former indicates that the system restricts the creation of new threads, such as excessive number of threads, which indicates that the second parameter represents an illegal thread property value. After the thread is created successfully, the newly created thread runs the function identified by parameter three and parameter four, and the original thread continues to run the next line of code.

Three Pthread_join Pthread_exit
   Pthread_join (pthread_t,&thread_result);
The function pthread_join is used to wait for the end of a thread. The function prototypes are:
extern int Pthread_join __p ((pthread_t __th, void **__thread_return));
The first parameter is the waiting thread identifier, and 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 invokes it waits until the thread that is waiting ends, and when the function returns, the resource that is waiting for the thread is retracted. There are two ways to end a thread, one is like our example above, the function ends, the thread that calls it ends, and the other is implemented by the function Pthread_exit. Its function prototypes are:
extern void Pthread_exit __p ((void *__retval)) __attribute__ ((__noreturn__));
The only argument is the return code of the function, as long as the second parameter in Pthread_join Thread_return is not NULL, this value is passed to Thread_return. Finally, one thread cannot be waited by multiple threads, or the first line that receives the signal Cheng returns, and the remaining thread that calls Pthread_join returns the error code esrch.
In this section, we have written one of the simplest threads and mastered the three most commonly used 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.


Mutex correlation

Mutexes are used to guarantee that only one thread is executing a piece of code over a period of time.

One int Pthread_mutex_init (pthread_mutex_t*, attribute *);

The function pthread_mutex_init is used to generate a mutex lock. A null parameter indicates that the default property is used. If you need to declare a mutex for a particular property, call the function Pthread_mutexattr_init. The function pthread_mutexattr_setpshared and the function Pthread_mutexattr_settype are used to set the Mutex property. The previous function sets the property pshared, which has two values, pthread_process_private, and pthread_process_shared. The former is used for thread synchronization in different processes, and the latter is used to synchronize different threads of the process. In the example above, we are using the default attribute 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 the different mechanisms of the upper, the unlock, and, in general, the last default attribute.

Two Pthread_mutex_lock Pthread_mutex_unlock pthread_delay_np

The Pthread_mutex_lock declaration begins with a mutex lock, and thereafter the code is locked until the call Pthread_mutex_unlock, i.e. only one thread can invoke execution at the same time. When a thread executes to pthread_mutex_lock, if the lock is being used by another thread at this point, the thread is blocked, that is, the program waits for the other thread to release the mutex.



Attention:

1 It is necessary to note that the above two sleep is not only for the purpose of demonstration, but also to let the thread sleep for some time, let the thread release the mutex, waiting for another thread to use the lock. The issue is described in reference 1 below. But there seems to be no pthread_delay_np that function under Linux (I tried to hint that there is no reference to the function), so I used sleep instead, but in reference 2 I gave another way, as if by Pthread_cond_ Timedwait to replace, there is a way to achieve.

2 Please pay attention to the comment comment1-5, which is the problem I have spent a few hours to find out.
If there is no comment1 and COMMENT4,COMMENT5, it will lead to a segment error at the time of Pthread_join, in addition, the above Comment2 and comment3 is the root cause, so you must remember to write the full code. Because the thread above may not have been created successfully, it is impossible to wait until that thread ends, and a segment error (Access to the unknown memory area) occurs when using Pthread_join. Also, when using memset, you need to include the string.h header file.

Linux C multithreaded programming

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.