The first experience of multithreading learning

Source: Internet
Author: User

Hello everyone, I am camellian. Recently involved in multi-threading, because it is just contact, but also need to improve, so the first just finishing notes to share with you, I hope you pass by the great gods, a lot of advice

Well, let's get down to the bottom, and learn the concepts of processes and threads first:

(1) A running program in iOS is a process or a task.

(2) A process contains at least one thread, and the thread is the execution flow of the program

A thread is the smallest unit of execution of a program ——— it can consume memory and CPUs to perform operations.

(3) When the iOS program starts, it starts running a thread at the same time that the process is created, which is called the main thread.

Note: The main thread is the final parent thread of other threads, and all interface display operations must be performed on the main thread

(4) The background thread cannot update the UI interface and respond to user click events

(5) Each process in the system has its own independent virtual memory space, while multiple threads in the same process share the memory space of the process

Every new thread created consumes a certain amount of memory and CPU time.

Thread safety is a concern when multiple threads compete for the same resource

Advantage:

1) give full play to the multi-core processor, assign different thread tasks to different processors, and really enter the "parallel operation" state

2) Assigning time-consuming, polling, or concurrency-demanding tasks to other threads and being responsible for unifying the update interface by the main thread will make the application smoother and the user experience better

3) When the number of hardware processors increases, the program runs faster without any adjustments

Difficulties:

1) "Contention" for shared resources

Multithreading is to accomplish multiple tasks synchronously, not to improve the efficiency of the operation, but to improve the overall performance of the system by increasing the efficiency of resource utilization.

Application Scenarios:

Time-consuming operations, such as network images, videos, songs, books and other resources to download; in-game sound playback

Threading Technology in iOS:

Nsthread each Nsthread object corresponds to a thread, which is lighter in magnitude

Nsoperation/nsoperationqueue Object-oriented threading technology

Gcd--grand Central Dispatch is a C-based framework that makes full use of multicore and is the recommended multithreaded technology for Apple

These three ways of programming from top to bottom, the level of abstraction from low to high, the higher the abstraction of the more simple to use, is also the most recommended for Apple. But for now, iOS developers need to be aware of the basic use of three of multithreaded technologies. Because many of the framework technologies use different multithreading techniques, respectively.

Multithreading on the Linux/unix platform:

Multithreaded development already has a mature pthread library support on the Linux platform. The most basic concepts involved in multithreaded development include three points: threads, mutexes, conditions.

Among them, the thread operation and the creation of threads, exit, waiting for 3 kinds.

The mutex consists of 4 operations, namely, create, destroy, lock and unlock.

There are 5 actions for conditional operations: Create, Destroy, Trigger, broadcast, and wait. Other thread extension concepts, such as semaphores, can be encapsulated by the basic operation of the three basic elements above.

------------------------------------------------------------

Object Operations Linux pthread API

-------------------------------------------------------------

Thread creation pthread_create

Exit Pthread_exit

Waiting for Pthread_join

-----------------------------------------------------------

Mutual exclusion lock creation Pthread_mutex_init

Destroying Pthread_mutex_destroy

Locking Pthread_mutex_lock

Unlock pthread_mutex_unlock

------------------------------------------------------------

Condition creation Pthread_cond_init

Destroying Pthread_cond_destroy

Trigger pthread_cond_signal

Broadcast Pthread_cond_broadcast

Waiting for pthread_cond_wait

Pthread_cond_timedwait

-------------------------------------------------------------

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 pthread_create

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. When creating a line Cheng, the function returns 0, if not 0, the creation thread fails, and the common error return code is 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

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.

A pthread_mutex_init

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.

Http://blog.sina.com.cn/s/blog_4673bfa50100bjy8.html

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.

Note: Send welfare, O (∩_∩) o~ in order to facilitate everyone to further deepen the impression, under the small master has to write their own some multithreaded instances posted, for your reference:

Instance Program One:

  

#include <stdio.h>

#include <pthread.h>

#include <unistd.h>//sleep ()

void *pickpeach ()

{

for (int i = 1; I <=; i + +)

{

printf ("Pick%i??" \ n ", i);

Sleep (1);

}

When things are done, the child threads need to exit

Pthread_exit (0);

}

void *pickbanana ()

{

for (int i = 1; I <=; i + +)

{

printf ("Take the%i root??" \ n ", i);

Sleep (1);

}

Pthread_exit (0);

}

int main (int argc, const char * argv[])

{

1. Preparing the Thread resource descriptor

pthread_t t1[2];

2. Create a sub-thread-pick??

int flag = Pthread_create (&t1[0], NULL, Pickpeach, NULL);

if (flag = = 0)

{

printf ("Pick?? thread creation succeeded \ n ");

}

Else

printf ("Pick?? Thread creation failed \ n ");

3. Create another sub-thread = = pick??

int flagbanana = Pthread_create (&t1[1], NULL, Pickbanana, NULL);

if (Flagbanana = = 0)

{

printf ("Pick?? thread creation succeeded \ n ");

}

Else

printf ("Pick?? Thread creation failed \ n ");

Sleep (15);

4. Waiting for thread to end

Pthread_join (T1[0], NULL);

Pthread_join (t1[1], NULL);

return 0;

}

Instance program two:

  

#include <stdio.h>

#include <pthread.h>

#include <unistd.h>//sleep

#include <string.h>//memset

Define a global variable

int mynumber = 0;

1.0 Preparing the Mutex descriptor

pthread_mutex_t T_mutex;

void *addt ()

{

for (int i = 1; i <; i + +)

{

Plus Mutual exclusion lock

Pthread_mutex_lock (&t_mutex);

mynumber++;

After the operation is complete, unlock

Pthread_mutex_unlock (&t_mutex);

printf ("addt:mynumber=%i\n", MyNumber);

Sleep (1);

}

Pthread_exit (0);

}

void *subt ()

{

for (int i = 1; i <; i + +)

{

Plus Mutual exclusion lock

Pthread_mutex_lock (&t_mutex);

mynumber--;

printf ("subt:mynumber=%i\n", MyNumber);

After the operation is complete, unlock

Pthread_mutex_unlock (&t_mutex);

Sleep (1);

}

Pthread_exit (0);

}

int main (int argc, const char * argv[])

{

1.0.1 initializing mutexes

Pthread_mutex_init (&t_mutex,null);

1.1 Preparing 2 thread descriptors

pthread_t mythread[2];

1.2 Empty array to 0

memset (&mythread, 0, sizeof (myThread));

2. Creation of 2 sub-threads

if (0 = = Pthread_create (MyThread, NULL, AddT, NULL))

{

printf ("Create + thread succeeded \ n");

}

if (0 = = Pthread_create (&mythread[1], NULL, SUBT, NULL))

{

printf ("Create-thread succeeded \ n");

}

3. Wait for the child thread to end

Pthread_join (Mythread[0], NULL);

Pthread_join (mythread[1], NULL);

return 0;

}

Instance Program three:

  

#include <stdio.h>

#include <pthread.h>

#include <unistd.h>//sleep

#include <string.h>//memset

typedef struct MYSTR

{

int A;

int b;

}hero;

Do a summation operation

void *addnumber (void *t)

{

int a = * (int*) t;

int s = 0;

for (int i = 0; I <= A; i + +)

{

s + = i;

}

printf ("s =%i\n", s);

Pthread_exit (0);

}

Do 2 numbers of additions

void *addnumberaandb (void *t)

{

Hero Tmphero = * (hero*) t;

printf ("a+b =%i\n", TMPHERO.A+TMPHERO.B);

Pthread_exit (0);

}

int main (int argc, const char * argv[])

{

1. Create 2 thread descriptors

pthread_t st[2];

2. Empty array

memset (St, 0, sizeof (ST));

3.1 Creating a sub-line Cheng

int B = 8;

Pthread_create (St, NULL, Addnumber, &b);

3.2 Creating a child thread two: performing an addition of 2 numbers

Hero Superman;

Superman.a = 3;

superman.b = 4;

Pthread_create (&st[1], NULL, addnumberaandb, &superman);

4. Wait for the child thread to finish executing

Pthread_join (St[0], NULL);

Pthread_join (st[1], NULL);

return 0;

}

All rights reserved ,Camelian e-mail address: [email protected]

The first experience of multithreading learning

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.