Example of C language multi-thread programming in Linux

Source: Internet
Author: User

LinuxLowerCMulti-thread programming example

2007Year 11Month 29Day Thursday10: 39

When learning things, examples are often the most interesting. I always learn basic theories and don't do it. I feel no sense of accomplishment.

The following is an example. We create two threads to increase the number of threads.
Maybe this instance has no practical value, but with a slight change, we can use it elsewhere.

Below is ourCode:

/* Thread_example.c: C multiple thread programming in Linux

* Author: Falcon

* E-mail: tunzhj03@st.lzu.edu.cn

*/

# 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 thread*/

If (temp = pthread_create (& Thread [0], null, thread1, null ))! = 0) // comment2

Printf ("Thread1Creation failed! \ N ");

Else

Printf ("Thread1Created\ N ");

 

If (temp = pthread_create (& Thread [1], null, thread2, null ))! = 0) // comment3

Printf ("Thread2Creation failed");

Else

Printf ("Thread2Created\ N ");

}

 

Void thread_wait (void)

{

/*Wait until the thread ends*/

If (thread [0]! = 0) {// comment4

Pthread_join (thread [0], null );

Printf ("Thread1Ended\ N ");

}

If (thread [1]! = 0) {// comment5

Pthread_join (thread [1], null );

Printf ("Thread2Ended\ N ");

}

}

 

Int main ()

{

/*Use the default attribute to initialize the mutex lock.*/

Pthread_mutex_init (& Mut, null );

 

Printf ("I am a main function. I am creating a thread.\ N ");

Thread_create ();

Printf ("I am the main function. I am waiting for the thread to complete the task.\ N ");

Thread_wait ();

 

Return 0;

}

 

Next let's compile and execute

Citation:


Falcon @ Falcon :~ /Program/C/code/FTP $ gcc-lpthread-O thread_example thread_example.c
Falcon @ Falcon :~ /Program/C/code/FTP $./thread_example
I am a main function. I am creating a thread.
Thread1 Created
Thread 2 Created
I am the main function. I am waiting for the thread to complete the task.
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 complete the task?
Thread 1 Ended
Thread2: Is the main function waiting for me to complete the task?
Thread 2 Ended

The annotations in the instance code should be clear. Next I will introduce several functions and variables mentioned above on the Internet for reference.

Citation:


Thread-related operations

IPthread_t

Pthread_t in the header file/Usr/include/bits/pthreadtypes. hDefinition:
Typedef unsigned long int pthread_t;
It is the identifier of a thread.

IIPthread_create

FunctionPthread_createUsed to create a thread. Its prototype is:
Extern int pthread_create _ p (pthread_t * _ thread, _ const pthread_attr_t * _ ATTR,
Void * (* _ start_routine) (void *), void * _ Arg ));
The first parameter is the pointer to the thread identifier. The second parameter is used to set the thread attribute. The third parameter is the starting address of the thread running function, and the last parameter is the parameter of the running function. Here, our functionsThreadNo parameter is required, so the last parameter is set as a null pointer. We also set the second parameter as a null pointer to generate a thread with the default attribute. The setting and modification of thread attributes will be described in the next section. When the thread is successfully created, the function returns0, If not0The thread creation fails. The common error code returned isEagainAndEinval. The former indicates that the system restricts the creation of new threads. For example, the number of threads is too large. The latter indicates that the second parameter indicates that the thread attribute value is invalid. After the thread is successfully created, the newly created thread runs the function with parameters 3 and 4, and the original thread continues to run the next line of code.

3. Pthread_join pthread_exit

Function Pthread_join Wait for the end of a thread. Function prototype:
Extern int pthread_join _ p (pthread_t _ th, void ** _ thread_return ));
The first parameter is the identifier of the waiting thread, and the second parameter is a user-defined pointer, which can be used to store the return value of the waiting thread. This function is a thread-blocking function. The function called will wait until the end of the waiting thread. When the function returns, the resources of the waiting thread will be reclaimed. There are two ways to end a thread. One is that when a function ends, the thread that calls it ends, and the other is through a function. Pthread_exit . Its function prototype is:
Extern void pthread_exit _ p (void * _ retval) _ attribute _ (_ noreturn __));
The only parameter is the code returned by the function, as long Pthread_join The second parameter in Thread_return No Null , This value will be passed Thread_return . It should be noted that a thread cannot be waited by multiple threads; otherwise, the first thread receiving the signal will return successfully, and other callsPthread_join The thread returns the error code. Esrch .
In this section, we have compiled the simplest thread and mastered the three most commonly used functions. Pthread_create , Pthread_join And Pthread_exit . Next, let's take a look at some common attributes of the thread and how to set these attributes.

Mutex lock

Mutex lock is used to ensure that only one thread is executing a piece of code within a period of time.

IPthread_mutex_init

FunctionPthread_mutex_initUsed to generate a mutex lock.NullThe parameter indicates that the default attribute is used. To declare a mutex lock for a specific attribute, you must call a function.Pthread_mutexattr_init. FunctionPthread_mutexattr_setpsharedAnd functionsPthread_mutexattr_settypeUsed to set the mutex lock attribute. Previous function setting attributePshared, It has two values,Pthread_process_privateAndPthread_process_shared. The former is used to synchronize threads in different processes, and the latter is used to synchronize different threads in the process. In the above example, we use the default attributePthread_process _ private. The latter is used to set the mutex lock type. Optional types includePthread_mutex_normal,Pthread_mutex_errorcheck,Pthread_mutex_recursiveAndPthread _ mutex_default. They define different on-board and unlock mechanisms. Generally, the last default attribute is used.

IIPthread_mutex_lock pthread_mutex_unlock pthread_delay_np

Pthread_mutex_lockThe Declaration starts to lock with mutex lock, and subsequent code is calledPthread_mutex_unlockSo far, they are locked, that is, they can only be called and executed by one thread at a time. When a thread executesPthread_mutex_lockIf the lock is used by another thread at this time, the thread is blocked, that isProgramWait until another thread releases the mutex lock.

Note:

1 It should be noted that the above two pointsSleepIt is not only for demonstration purposes, but also for the thread to sleep for a period of time, so that the thread releases the mutex lock and waits for another thread to use this lock. The following references1This problem is described in. HoweverLinuxNoPthread_delay_npThe function (I tried it and prompted that the reference of the function was not defined), so I usedSleepBut references2InPthread_cond_timedwaitIn this example, an implementation method is provided.

Pay attention to the comments.Comment1-5It took me a few hours to figure out the problem.
If noComment1AndComment4, comment5,Will causePthread_joinIn addition, the aboveComment2AndComment3Is the root cause, so remember to write the full code. Because the above thread may not have been created successfully, it is impossible to wait until the end of the thread,Pthread_joinWhen the block error occurs (access to the unknown memory zone ). In additionMemsetYou must includeString. hHeader file

References:

1.LinuxMulti-Thread Programming

2. Pthread_delay_np(The header here is about POSIX.Example of conditional variables)

3. Pthread_joinAnd segment error (Thank you very much for your attention)

4. POSIXThread Programming Guide [learn LinuxMultithreading. If you don't look at this, you will regret it.]
Http://www.linuxforum.net/forum/showflat.php? Cat = & board = Program & number = 294073 & page = 0 & view = collapsed & SB = 5 & O = 7 & fpart = http://www.bczs.net/xml/2005/11/5/4374188.xmlhttp://bbs.chinaunix.net/archiver? Tid-584593.htmlhttp: // linux.chinaunix.net/doc/program/2001-08-11/642.shtml

 

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.