Linux multitasking programming--threading

Source: Internet
Author: User

Threading Basics

Because the address space of the process is private, the system overhead is greater when the context switches

Threads created in the same process share the Process's address space

Typically threads are worth multiple tasks that share the same address space

Private these private resources for each thread: thread id, PC (program counter) and related register, stack {local variable, function return address}, error number, signal mask and priority, execution state and properties

  Inter-thread synchronization and mutual exclusion mechanisms are: semaphores, mutexes, condition variables

1---thread-related functions

In Linux generally through the Third-party line libraries to achieve: the following is mainly the New POSIX thread Library (NPTL);

#include <pthread.h>

int pthread_create (pthread_t *thread, const pthread_attr_t *attr, void * (*routine) (void *), void *arg); Create a new thread

Thread: threads to be created attr: specified thread property, null for default property routine: function to execute in thread argv: arguments passed to the function executed by the thread

Return key succeeded: 0 error: wrong number

int pthread_join (pthread_t thread, void **value_ptr); Wait for the end of a thread

Thread: threads to wait for; value_ptr: pointer *value_ptr to the parameters returned by the thread

Return value succeeded: 0 error: wrong number

void Pthread_exit (void *value_ptr);//exit thread

Value_ptr: return value when thread exits

int Pthread_cancel (pthread_t thread); Send a terminating signal to a thread

Thread: the process to send the signal

2---multithreaded Programming Example

1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4#include <pthread.h>5 6 Charmessage[ +] ="Hello world";7 void*thread_function (void*arg);8 9 intMainintargcChar*Argv[])Ten { one pthread_t a_thread; a     void*thread_result; -      -    if(pthread_create (&a_thread, NULL, thread_function, (void*) Message) <0);//Create a thread with default properties the    { -Perror ("fail to pthread create"); -Exit (-1); -     } +printf"waiting for thread to finish\n"); -     if(pthread_join (a_thread, &thread_result) <0)//wait for thread to end +     { aPerror ("fail to pthread join"); atExit (-1);  -     } -printf"MESSAGE is now%s\n", message); -  -     return 0; - } in  - void*thread_function (void*Arg) to { +   -srtcpy (message,"marked by thread"); thePthread_exit ("Thank for The CPU time"); *}

3---compiling Multi-threaded Threads

# Gcc-o Sample Sample.c-lpthread-d_reentrant

-lpthred:; Link Pthread Library

-d_reentrant: Generating Reentrant Code

Pthread_key_create (); Thread private Data Unix/linux the principle and use method of private data realization

4---thread Pool Thread_pool

Most web servers, including Web servers, have a feature of having to process a large number of connection requests per unit of time, but the processing time is relatively short. This is done in the traditional multithreaded server model: once a request arrives, a new thread is created, the thread executes the task, and the thread exits after the task has finished Executing. This is the "instant create, instant destroy" strategy. Although the time to create a thread has been greatly shortened compared to the creation process, the server will be in a state of creating threads and destroying threads if the task being committed to the thread is a short execution time and the number of executions is very frequent. This overhead is not negligible, especially when the thread is executing very, very short.

The thread pool is to solve the above problem, it is the principle of implementation: after the application started, immediately create a certain number of threads, into the idle Queue. These threads are in a blocking state, and these threads occupy only a small amount of the cpu. When the task arrives, the thread pool selects an idle thread to run the task into this thread. When all threads are in the process of processing tasks, the thread pool automatically creates a certain number of new threads to handle more tasks. The thread does not exit after the execution of the task, but continues to wait for the next task in the Threads Pool. When most threads are in a blocking state, the thread pool automatically destroys a subset of the threads and reclaims system Resources.

Below is a simple thread pool implementation, This thread pool code is I refer to an example on the Internet to achieve, because can not find the source, there is no way to indicate where the reference from. The scenario is this: before the program starts, the thread pool is initialized, threads in the thread pools are started, all threads in the thread pool are blocked because no tasks have arrived, and when a task arrives, a free thread is removed from the thread pool, and if all the threads are working, they are added to the queue and Queued. If the number of tasks in the queue is greater than the maximum number that the queue can hold, you cannot add tasks to the queue, only wait for the queue to be satisfied to add tasks to the Queue.

Implementation code: Simple Linux thread pool http://www.cnblogs.com/venow/archive/2012/11/22/2779667.html

Linux multitasking programming--threading

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.