Multi-threaded client/server implementation in Linux system

Source: Internet
Author: User
Tags requires terminates thread

In a traditional UNIX model, when a process needs to be executed by another entity, the process derives (fork) a subprocess, allowing the child processes to process. Most Web server programs under UNIX are written in such a way that the parent process accepts the connection, derives the child process, and processes the interaction with the customer.

Although this model has been used well for many years, there are some problems with fork:

The 1.fork is expensive. The memory image is copied from the parent process to the child process, all the descriptors are replicated in the subprocess, and so on. Currently, UNIX implementations use a technique called write-time copy (copy-on-write) to avoid copying the parent process data space to the child process. Despite this optimization technology, fork is still expensive.

2.fork subprocess requires interprocess communication (IPC) to pass information between parent and child processes. The information before fork is easy to pass because the child process has a copy of the parent process data space and all the descriptive words from the beginning. But returning information from a child process to the parent process requires more work.

Threads help solve both of these problems. Threads are sometimes referred to as light weight processes (lightweight process), because threads are "lighter" than processes, and in general, creating a thread is 10~100 times faster than creating a process.

All threads in a process share the same global memory, which makes it easy for threads to share information, but this simplicity also poses a synchronization problem.

All threads in a process share not only global variables but also shared: process directives, most data, open files (such as descriptors), signal handlers and signal disposal, current working directory, user ID, and group IDs. But each thread has its own thread ID, register set (including program counters and stack pointers), stacks (for local variables and return addresses), error, signal mask, priority. In Linux thread programming conforms to the POSIX.1 standard, called Pthreads. All pthread functions begin with the Pthread_. The following 5 basic thread functions are described, including the Pthread.h header file before calling them. Then give an example of a TCP client/server program written with them.

First function:

int pthread_create
(pthread_t *tid,const pthread_attr_t *attr,void *
(*func)(void *),void *arg);

Each thread in a process is identified by a thread ID (thread ID) whose data type is pthread_t (often unsigned int). If a new thread is created successfully, its ID is returned through the TID pointer.

Each thread has many attributes: priority, starting stack size, whether it should be a daemon, and so on, and when creating threads, we can override the defaults by initializing a pthread_attr_t variable to describe these properties. We usually use the default value, in which case we describe the attr parameter as a null pointer.

Finally, when you create a thread, we describe a function that it will execute. Thread to invoke the function and then either explicitly terminate (call Pthread_exit) or implicitly terminate (let the function return). The address of the function is specified by the Func parameter, the invocation parameter of the function is a pointer arg, and if we need multiple invocation parameters, we must package them into a struct and pass the address as a unique argument to the starting function.

In the declarations of Func and ARG, the Func function takes a universal pointer (void *) parameter and returns a generic pointer (void *), which allows us to pass a pointer (pointing to whatever we want to point to) to the thread, A pointer is returned by the thread (also pointing to anything we want to point to). The call succeeds, returns 0, and returns a positive EXXX value when an error occurs. The Pthread function does not set errno.

Second function:

int pthread_join(pthread_t tid,void **status);

The function waits for a thread to terminate. Comparing threads to processes, pthread_creat is similar to fork, and Pthread_join is similar to Waitpid. We have to wait for the thread to TID, unfortunately, we have no way to wait for any thread to end. If the status pointer is not empty, the return value of the thread (a pointer to an object) is stored where the status points.

A third function:

pthread_t pthread_self(void);

Threads have an ID to identify themselves within a given process. The thread ID is returned by pthread_creat, and we can pthread_self get our own thread ID.

A fourth function:

int pthread_detach(pthread_t tid);

Threads are either confluent (joinable) or detached (detached). When a confluent thread terminates, its thread ID and exit state are retained until another thread invokes Pthread_join. A detached thread is like a daemon: when it terminates, all the resources are released and we cannot wait for it to terminate. If a thread needs to know when another thread terminates, it is best to keep the convergence of the second thread. The Pthread_detach function changes the specified thread to a detached. The function is usually called out of its own thread, such as: Pthread_detach (Pthread_self ());

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.