Intorduction | About Threaded Programming | Thread Management | Run Loops
Synchronization | Thread Safety Summary | Glossary

본 페이지는 Threading Programming Guide 문서의 About Threaded Programming 부분을 번역해 놓은 페이지 입니다. 발 번역이라 이상한 부분이 있을 수 있습니다. 발견즉시 댓글을 달아 주세요.


About Threaded Programming
쓰레드 프로그래밍에 관해서

For many years, maximum computer performance was limited largely by the speed of a single microprocessor at the heart of the computer. As the speed of individual processors started reaching their practical limits, however, chip makers switched to multicore designs, giving the computer the opportunity to perform multiple tasks simultaneously. And although OS X takes advantage of these cores whenever it can to perform system-related tasks, your own applications can also take advantage of them through threads.

많은 년간, 최대 컴퓨터 성능은 컴퓨터의 중심에 하나의 마이크로 프로세서의 속도에 의해 크게 제한되었다. 각 프로세서의 속도가 실제 한계에 도달하기 시작으로, 그러나, 칩 제조업체는 컴퓨터에게 동시에 여러 작업을 수행 할 수있는 기회를 제공, 설계를 멀티 코어로 전환. 때마다 시스템 관련 작업을 수행 할 수있는 OS X이 코어를 활용하지만, 당신의 자신의 응용 프로그램은 스레드를 통해 활용할 수 있습니다.

What Are Threads?
쓰레드는 무엇인가?

Threads are a relatively lightweight way to implement multiple paths of execution inside of an application. At the system level, programs run side by side, with the system doling out execution time to each program based on its needs and the needs of other programs. Inside each program, however, exists one or more threads of execution, which can be used to perform different tasks simultaneously or in a nearly simultaneous manner. The system itself actually manages these threads of execution, scheduling them to run on the available cores and preemptively interrupting them as needed to allow other threads to run.

스레드 응용 프로그램 내에서 여러 실행 경로를 구현하는 비교적 간단한 방법입니다.시스템 레벨에서, 프로그램은 시스템이 요구 사항과 다른 프로그램의 필요에 따라 각 프로그램의 실행 시간을 해주기 때문에와 나란히 실행합니다. 각 프로그램 내에서, 그러나, 동시에 또는 거의 동시에 방법으로 다른 작업을 수행 할 수 있습니다 실행 스레드를 하나 이상 존재.시스템 자체는 실제로 사용 가능한 코어에서 실행하도록 예약하고 선제 적들을 다른 스레드를 실행할 수 있도록하는 데 필요한 중단, 실행이 스레드를 관리합니다.

From a technical standpoint, a thread is a combination of the kernel-level and application-level data structures needed to manage the execution of code. The kernel-level structures coordinate the dispatching of events to the thread and the preemptive scheduling of the thread on one of the available cores. The application-level structures include the call stack for storing function calls and the structures the application needs to manage and manipulate the thread’s attributes and state.

기술적 인 관점에서, 스레드는 커널 수준의 코드의 실행을 관리하는 데 필요한 응용 프로그램 수준 데이터 구조의 조합입니다.커널 레벨의 구조는 사용 가능한 코어 중 하나의 스레드와 스레드의 선점 스케줄링 이벤트 디스패치를 조정. 응용 프로그램 수준의 구조는 저장 함수를 호출하고 응용 프로그램 스레드의 특성과 상태를 관리하고 조작하는 데 필요한 구조에 대한 호출 스택 (가) 있습니다.

In a non-concurrent application, there is only one thread of execution. That thread starts and ends with your application’s main routine and branches one-by-one to different methods or functions to implement the application’s overall behavior. By contrast, an application that supports concurrency starts with one thread and adds more as needed to create additional execution paths. Each new path has its own custom start routine that runs independently of the code in the application’smain routine. Having multiple threads in an application provides two very important potential advantages:

비 동시 응용 프로그램에서 실행 한 스레드가있다. 해당 스레드는 응용 프로그램의 주 루틴 가지 다른 방법이나 응용 프로그램의 전반적인 동작을 구현하는 기능을 하나씩 시작하고 끝납니다. 대조적으로, 동시성을 지원하는 응용 프로그램은 하나의 스레드로 시작하고 추가 실행 경로를 생성하는 데 필요한 더 추가합니다. 각각의 새 경로는 독립적으로 application'smain 루틴에서 코드를 실행하는 자신의 사용자 정의 시작 루틴을 가지고 있습니다.응용 프로그램에서 여러 스레드를 갖는 것은 매우 중요한 두 가지 잠재적 인 이점을 제공합니다 :

  • Multiple threads can improve an application’s perceived responsiveness.
    다중 스레드 응용 프로그램의인지 응답을 개선 할 수 있습니다.

  • Multiple threads can improve an application’s real-time performance on multicore systems.
    여러 스레드가 멀티 코어 시스템에서 응용 프로그램의 실시간 성능을 향상시킬 수 있습니다.

If your application has only one thread, that one thread must do everything. It must respond to events, update your application’s windows, and perform all of the computations needed to implement your application’s behavior. The problem with having just one thread is that it can only do one thing at a time. So what happens when one of your computations takes a long time to finish? While your code is busy computing the values it needs, your application stops responding to user events and updating its windows. If this behavior continues long enough, a user might think your application is hung and try to forcibly quit it. If you moved your custom computations onto a separate thread, however, your application’s main thread would be free to respond to user interactions in a more timely manner.

응용 프로그램은 하나의 스레드가있는 경우, 그 하나의 쓰레드가 모든 작업을 수행해야합니다. 이것은 이벤트에 응답 응용 프로그램의 윈도우를 업데이트하고 응용 프로그램의 동작을 구현하는 데 필요한 계산을 모두 수행해야합니다. 단지 하나의 스레드를 갖는 문제는 한 번에 하나의 일을 할 수 있다는 것입니다. 귀하의 계산 중 하나 완료하는 데 오랜 시간이 걸리는 경우 그래서 어떻게됩니까? 코드는 필요한 값 바쁜 컴퓨팅이지만, 응용 프로그램은 사용자 이벤트에 응답하고 윈도우를 업데이트하지 않습니다. 이 문제가 오랫동안 계속되면, 사용자는 응용 프로그램이 걸려 생각하고 강제로 종료하려고 할 수도 있습니다. 당신이 별도의 스레드에 사용자 정의 계산을 이동 한 경우, 그러나, 응용 프로그램의 주 스레드는 더 적시에 사용자 상호 작용에 응답하여 주시기 될 것입니다.

With multicore computers common these days, threads provide a way to increase performance in some types of applications. Threads that perform different tasks can do so simultaneously on different processor cores, making it possible for an application to increase the amount of work it does in a given amount of time.

요즘 일반적인 컴퓨터를 멀티 코어 스레드는 일부 유형의 응용 프로그램 성능을 향상하는 방법을 제공합니다. 다른 작업을 수행하는 쓰레드는 가능한 응용 프로그램이 지정된 시간에가하는 일의 양을 증가하기 위해 만드는 다른 프로세서 코어에 이렇게 동시에 수행 할 수 있습니다.

Of course, threads are not a panacea for fixing an application’s performance problems. Along with the benefits offered by threads come the potential problems. Having multiple paths of execution in an application can add a considerable amount of complexity to your code. Each thread has to coordinate its actions with other threads to prevent it from corrupting the application’s state information. Because threads in a single application share the same memory space, they have access to all of the same data structures. If two threads try to manipulate the same data structure at the same time, one thread might overwrite another’s changes in a way that corrupts the resulting data structure. Even with proper protections in place, you still have to watch out for compiler optimizations that introduce subtle (and not so subtle) bugs into your code.

물론, 스레드 애플리케이션의 성능 문제를 해결하기위한 만병 통치약이 아닙니다. 함께 스레드에 의해 제공되는 혜택은 잠재적 인 문제를 온다.응용 프로그램의 여러 실행 경로를 갖는 코드의 복잡성 상당한 양의를 추가 할 수 있습니다. 각 스레드는 응용 프로그램의 상태 정보를 손상시키지 않도록하기 위해 다른 스레드의 작업을 조정합니다.하나의 응용 프로그램의 스레드가 같은 메모리 공간을 공유하기 때문에, 그들은 동일한 데이터 구조의 모든에 액세스 할 수 있습니다. 두 스레드가 동시에 같은 데이터 구조를 조작하려고하면, 하나의 스레드는 결과 데이터 구조가 손상 방법으로 다른 사람의 변경 내용을 덮어 쓸 수 있습니다. 심지어 장소에 적절한 보호와 함께, 당신은 여전히 귀하의 코드에 미묘 (그래서 미묘한) 버그를 소개 컴파일러 최적화를 조심해야합니다.

Threading Terminology
스레딩 용어

Before getting too far into discussions about threads and their supporting technologies, it is necessary to define some basic terminology.
스레드과 지원 기술에 대한 논의에 너무 멀리 얻기 전에, 몇 가지 기본 용어를 정의 할 필요가있다.

If you are familiar with UNIX systems, you may find that the term “task” is used differently by this document. On UNIX systems, the term “task” is used at times to refer to a running process.
당신은 UNIX 시스템에 익숙하다면, 당신은 용어 "작업"이 문서에서 다르게 사용되는 것을 알 수 있습니다. UNIX 시스템에서, 용어 "작업"실행중인 프로세스를 참조하는 시간에 사용됩니다.

This document adopts the following terminology:
이 문서에서는 다음 용어를 채택한다 :

  • The term thread is used to refer to a separate path of execution for code.
    용어는 스레드가 코드 별도의 실행 경로를 참조하는 데 사용됩니다.

  • The term process is used to refer to a running executable, which can encompass multiple threads.
    장기 과정은 여러 스레드를 포함 할 수있는 실행 실행을 참조하는 데 사용됩니다.

  • The term task is used to refer to the abstract concept of work that needs to be performed.
    용어 작업을 수행해야하는 작업의 추상적 인 개념을 참조하는 데 사용됩니다.

Alternatives to Threads
스레드에 대한 대안

One problem with creating threads yourself is that they add uncertainty to your code. Threads are a relatively low-level and complicated way to support concurrency in your application. If you do not fully understand the implications of your design choices, you could easily encounter synchronization or timing issues, the severity of which can range from subtle behavioral changes to the crashing of your application and the corruption of the user’s data.

스레드를 직접 만드는 하나의 문제는 그들이 코드에 불확실성을 추가하는 것입니다. 스레드 응용 프로그램에서 동시성을 지원하기 위해 상대적으로 낮은 수준의 복잡한 방법입니다. 당신이 완전히 디자인 선택의 의미를 이해하지 않는 경우에, 당신은 쉽게 동기화 또는 타이밍 문제, 미묘한 행동 변화에서 응용 프로그램과 사용자 데이터의 손상의 충돌에 이르기까지 다양 수의 심각도가 발생할 수 있습니다.

Another factor to consider is whether you need threads or concurrency at all. Threads solve the specific problem of how to execute multiple code paths concurrently inside the same process. There may be cases, though, where the amount of work you are doing does not warrant concurrency. Threads introduce a tremendous amount of overhead to your process, both in terms of memory consumption and CPU time. You may discover that this overhead is too great for the intended task, or that other options are easier to implement.

고려해야 할 또 다른 요소는 전혀 스레드 또는 동시성을 필요 여부입니다. 스레드가 동시에 동일한 프로세스 내에서 여러 개의 코드 경로를 실행하는 방법에 대한 특정 문제를 해결한다. 당신이하고있는 일의 양이 동시성을 보증하지 않습니다 어디 그러나, 경우가있을 수 있습니다. 스레드는 메모리 사용량과 CPU 시간의 측면에서, 프로세스에 오버 헤드 엄청난 양을 소개합니다. 이 오버 헤드는 다른 옵션을 구현하기 쉽게 원하는 작업, 또는 너무 큰 것을 발견 할 수 있습니다.

Table 1-1 lists some of the alternatives to threads. This table includes both replacement technologies for threads (such as operation objects and GCD) and alternatives that are geared towards efficiently using the single thread you already have.

표 1-1에게 스레드 대안의 일부를. 이 테이블은 스레드 (예 : 작업 개체와 GCD)와 효율적으로 당신은 이미 하나의 스레드를 사용하여 방향이 준비되어 있습니다 대안에 대한 대체 기술이 모두 포함됩니다.

Table 1-1  Alternative technologies to threads

Technology

Description

Operation objects

Introduced in OS X v10.5, an operation object is a wrapper for a task that would normally be executed on a secondary thread. This wrapper hides the thread management aspects of performing the task, leaving you free to focus on the task itself. You typically use these objects in conjunction with an operation queue object, which actually manages the execution of the operation objects on one or more threads.

OS X 10.5에 도입, 작업 개체는 일반적으로 보조 스레드에서 실행 될 작업에 대한 래퍼입니다. 이 래퍼는 작업 자체에만 집중할 수, 작업을 수행하는 스레드 관리 측면을 숨 깁니다. 당신은 일반적으로 실제로는 하나 이상의 스레드에서 작업 객체의 실행을 관리하는 작업 큐 개체와 함께 이러한 개체를 사용합니다.

For more information on how to use operation objects, see Concurrency Programming Guide.
작업 개체를 사용하는 방법에 대한 자세한 내용은 동시성 프로그래밍 가이드를 참조하십시오.

Grand Central Dispatch (GCD)

Introduced in Mac OS x v10.6, Grand Central Dispatch is another alternative to threads that lets you focus on the tasks you need to perform rather than on thread management. With GCD, you define the task you want to perform and add it to a work queue, which handles the scheduling of your task on an appropriate thread. Work queues take into account the number of available cores and the current load to execute your tasks more efficiently than you could do yourself using threads.

맥 OS X v10.6의에 도입, 그랜드 센트럴 디스패치를 사용하면 스레드 관리를 수행하는 대신해야하는 작업에 집중할 수 있도록 스레드에 대한 또 다른 대안입니다. GCD와 함께, 당신은 당신이 수행하고 해당 스레드에 작업의 스케줄링을 처리하는 작업 큐에 추가 할 작업을 정의합니다. 작업 큐 계정에 사용 가능한 코어의 수와 자신이 스레드를 사용 할 수있는 것보다 더 효율적으로 작업을 실행하는 현재의 부하를 가지고.

For information on how to use GCD and work queues, see Concurrency Programming Guide

GCD와 작업 큐를 사용하는 방법에 대한 자세한 내용은 동시성 프로그래밍 가이드를 참조하십시오

Idle-time notifications

For tasks that are relatively short and very low priority, idle time notifications let you perform the task at a time when your application is not as busy. Cocoa provides support for idle-time notifications using the NSNotificationQueue object. To request an idle-time notification, post a notification to the default NSNotificationQueue object using the NSPostWhenIdle option. The queue delays the delivery of your notification object until the run loop becomes idle. For more information, see Notification Programming Topics.

상대적으로 짧은 매우 낮은 우선 순위 작업의 유휴 시간 알림 응용 프로그램으로 사용 중이 아닐 때 시간에 작업을 수행 할 수 있습니다. 코코아 NSNotificationQueue 개체를 사용하여 유휴 시간 알림에 대한 지원을 제공합니다.유휴 시간 알림을 요청하려면 NSPostWhenIdle 옵션을 사용하여 기본 NSNotificationQueue 개체에 대한 알림을 게시 할 수 있습니다.런 루프가 유휴 상태가 될 때까지 대기열 알림 객체의 전달을 지연. 자세한 내용은 Notification 프로그래밍 항목을 참조하십시오.

Asynchronous functions

The system interfaces include many asynchronous functions that provide automatic concurrency for you. These APIs may use system daemons and processes or create custom threads to perform their task and return the results to you. (The actual implementation is irrelevant because it is separated from your code.) As you design your application, look for functions that offer asynchronous behavior and consider using them instead of using the equivalent synchronous function on a custom thread.

시스템 인터페이스는 당신을 위해 자동으로 동시성을 제공하는 많은 비동기 기능이 있습니다. 이 API는 시스템 데몬 및 프로세스를 사용하거나 자신의 작업을 수행하고 당신에게 결과를 반환하는 사용자 지정 스레드를 만들 수 있습니다. (그것은 당신의 코드에서 분리되어 있기 때문에 실제 구현은 무관하다.) 응용 프로그램을 설계 할 때, 비동기 동작을 제공하고이를 사용하는 대신 사용자 지정 스레드에서 해당 동기 기능을 사용하는 것이 함수를 찾습니다.

Timers

You can use timers on your application’s main thread to perform periodic tasks that are too trivial to require a thread, but which still require servicing at regular intervals. For information on timers, see “Timer Sources.”

당신은 스레드를 필요로하기에 너무 사소한,하지만 여전히 정기적으로 서비스 요구하는 정기적 인 작업을 수행하는 응용 프로그램의 주 스레드에서 타이머를 사용할 수 있습니다. 타이머에 대한 자세한 내용은 "타이머 소스"를 참조하십시오.

Separate processes

Although more heavyweight than threads, creating a separate process might be useful in cases where the task is only tangentially related to your application. You might use a process if a task requires a significant amount of memory or must be executed using root privileges. For example, you might use a 64-bit server process to compute a large data set while your 32-bit application displays the results to the user.

별도의 프로세스를 생성, 스레드보다 더 헤비급 작업 만 접선 응용 프로그램에 관련되는 경우에 유용 할 수 있지만. 작업이 상당한 양의 메모리를 필요로하거나 루트 권한을 사용하여 실행해야하는 경우는 프로세스를 사용할 수 있습니다. 예를 들어, 32 비트 응용 프로그램이 사용자에게 결과를 표시하면서 큰 데이터 집합을 계산하는 64 비트 서버 프로세스를 사용할 수 있습니다.

Threading Support
지원 스레딩

If you have existing code that uses threads, OS X and iOS provide several technologies for creating threads in your applications. In addition, both systems also provide support for managing and synchronizing the work that needs to be done on those threads. The following sections describe some of the key technologies that you need to be aware of when working with threads in OS X and iOS.

스레드를 사용하는 코드를 기존의 경우, OS X 및 IOS는 응용 프로그램에서 스레드를 생성하기위한 여러 가지 기술을 제공합니다. 또한 두 시스템은 해당 스레드에서 수행해야 할 작업을 관리하고 동기화에 대한 지원을 제공합니다.다음 섹션에서는 OS X 및 IOS의 스레드로 작업 할 때 알아 두어야 할 핵심 기술 중 일부를 설명합니다.

Threading Packages

스레딩 패키지

Although the underlying implementation mechanism for threads is Mach threads, you rarely (if ever) work with threads at the Mach level. Instead, you usually use the more convenient POSIX API or one of its derivatives. The Mach implementation does provide the basic features of all threads, however, including the preemptive execution model and the ability to schedule threads so they are independent of each other.

마하 수준에서 스레드와 스레드에 대한 기본 구현 메커니즘은 마하 스레드이지만, 당신은 거의 (면 적) 작동합니다. 대신, 당신은 일반적으로 더 편리 POSIX API 또는 그 유도체 중 하나를 사용하십시오.마하 구현은 선제 적 실행 모델들은 서로 독립적이되도록 스레드를 예약 할 수있는 능력을 포함한 모든 스레드의 기본 기능을하지만, 제공한다.

Listing 2-2 lists the threading technologies you can use in your applications.
목록 2-2는 응용 프로그램에서 사용할 수있는 스레딩 기술을 보여줍니다.

Table 1-2  Thread technologies

Technology

Description

Cocoa threads

Cocoa implements threads using the NSThread class. Cocoa also provides methods on NSObject for spawning new threads and executing code on already-running threads. For more information, see “Using NSThread” and “Using NSObject to Spawn a Thread.”

코코아 NSThread 클래스를 사용하여 스레드를 구현합니다. 코코아는 산란 새 스레드 NSObject의에 대한 방법과 이미 실행중인 스레드에서 실행되는 코드를 제공합니다. 자세한 내용은 "NSThread 사용"을 참조하십시오 "스레드를 생성하는 NSObject의 사용"을 참조하십시오.

POSIX threads

POSIX threads provide a C-based interface for creating threads. If you are not writing a Cocoa application, this is the best choice for creating threads. The POSIX interface is relatively simple to use and offers ample flexibility for configuring your threads. For more information, see“Using POSIX Threads”

POSIX 스레드는 스레드를 생성하기위한 C 기반의 인터페이스를 제공합니다. 당신은 코코아 응용 프로그램을 작성하지 않은 경우,이 스레드를 만들기위한 최고의 선택입니다.POSIX 인터페이스를 사용하는 비교적 간단하고 스레드를 구성하기위한 충분한 유연성을 제공합니다. 자세한 내용은 "POSIX 스레드 사용"을 참조하십시오

Multiprocessing Services

Multiprocessing Services is a legacy C-based interface used by applications transitioning from older versions of Mac OS. This technology is available in OS X only and should be avoided for any new development. Instead, you should use the NSThread class or POSIX threads. If you need more information on this technology, see Multiprocessing Services Programming Guide.

멀티 서비스는 Mac OS의 이전 버전에서 전환 응용 프로그램에서 사용하는 기존 C 기반의 인터페이스입니다. 이 기술은 OS X에서 사용할 수 있으며 새로운 발전을 위해 피해야한다. 대신에, 당신은 NSThread 클래스 또는 POSIX 스레드를 사용합니다. 이 기술에 대한 자세한 정보가 필요하면 멀티 프로세싱 서비스 프로그래밍 가이드를 참조하십시오.

At the application level, all threads behave in essentially the same way as on other platforms. After starting a thread, the thread runs in one of three main states: running, ready, or blocked. If a thread is not currently running, it is either blocked and waiting for input or it is ready to run but not scheduled to do so yet. The thread continues moving back and forth among these states until it finally exits and moves to the terminated state.

응용 프로그램 수준에서 모든 스레드는 다른 플랫폼에 본질적으로 동일한 방식으로 작동합니다. 준비, 또는 차단 실행 : 스레드를 시작하면 스레드는 세 가지 상태 중 하나에서 실행됩니다.스레드가 현재 실행되고 있지 않은 경우, 어느 차단하고 입력을 대기하거나 실행할 준비가 아직 그렇게 예정되어 있지 않습니다.스레드가 이러한 상태 사이를 앞뒤로 이동 계속 그것을 마지막으로 종료하고 종료 상태로 이동할 때까지.

When you create a new thread, you must specify an entry-point function (or an entry-point method in the case of Cocoa threads) for that thread. This entry-point function constitutes the code you want to run on the thread. When the function returns, or when you terminate the thread explicitly, the thread stops permanently and is reclaimed by the system. Because threads are relatively expensive to create in terms of memory and time, it is therefore recommended that your entry point function do a significant amount of work or set up a run loop to allow for recurring work to be performed.

당신은 새 스레드를 만들 때 해당 스레드에 대한 진입 점 함수 (또는 코코아 스레드의 경우 진입 점 방식)를 지정해야합니다. 이 엔트리 포인트 함수는 스레드에서 실행하고자하는 코드를 구성합니다.함수가 반환 할 때 또는 당신이 명시 적으로 스레드를 종료하면 스레드는 영구적으로 중지하고 시스템에 의해 회수된다. 스레드가 메모리와 시간의 관점에서 작성 상대적으로 고가이기 때문에, 따라서 귀하의 진입 점 함수가 상당한 양의 작업을 수행하거나 실행 루프를 수행 할 반복 작업이 가능하도록을 설정하는 것이 좋습니다.

For more information about the available threading technologies and how to use them, see “Thread Management.”

사용 가능한 스레딩 기술을 사용하는 방법에 대한 자세한 내용은 "스레드 관리"를 참조하십시오.

Run Loops

루프를 실행

A run loop is a piece of infrastructure used to manage events arriving asynchronously on a thread. A run loop works by monitoring one or more event sources for the thread. As events arrive, the system wakes up the thread and dispatches the events to the run loop, which then dispatches them to the handlers you specify. If no events are present and ready to be handled, the run loop puts the thread to sleep.

런 루프는 스레드에서 비동기 적으로 도착하는 이벤트를 관리하는 데 사용되는 인프라의 조각이다.런 루프는 스레드에 대해 하나 이상의 이벤트 소스를 모니터링하는 방식으로 작동합니다. 이벤트가 도착하면, 시스템은 스레드 실행 루프 전달 이벤트를 깨어 그 어느 지정 처리기 디스패치합니다. 어떤 이벤트가 존재하고 처리 할 준비가되지 않으면, 실행 루프는 잠을 스레드를 넣습니다.

You are not required to use a run loop with any threads you create but doing so can provide a better experience for the user. Run loops make it possible to create long-lived threads that use a minimal amount of resources. Because a run loop puts its thread to sleep when there is nothing to do, it eliminates the need for polling, which wastes CPU cycles and prevents the processor itself from sleeping and saving power.

당신은 당신이 만드는 모든 스레드가 실행 루프를 사용할 필요는 없습니다 만, 이렇게하면 사용자에게 더 나은 경험을 제공 할 수 있습니다. 루프가 가능한 최소한의 자원을 사용하여 수명이 긴 스레드를 만들 수 있도록 실행합니다.실행 루프 아무 상관이 없을 때 수면의 스레드를두고 있기 때문에, CPU 사이클을 낭비 전원을 자고 저장에서 프로세서 자체를 방지 폴링에 대한 필요가 없습니다.

To configure a run loop, all you have to do is launch your thread, get a reference to the run loop object, install your event handlers, and tell the run loop to run. The infrastructure provided by OS X handles the configuration of the main thread’s run loop for you automatically. If you plan to create long-lived secondary threads, however, you must configure the run loop for those threads yourself.

런 루프를 구성하려면, 당신이해야 할 모든 당신의 스레드를 실행 실행 루프 개체에 대한 참조를 얻을 이벤트 처리기를 설치하고 실행하는 실행 루프를 알 수 있습니다. OS X에서 제공하는 인프라는 자동으로 메인 스레드의 실행 루프의 구성을 처리합니다. 당신이 오래 지속 보조 스레드를 생성하려는 경우, 그러나, 당신은 그 스레드 직접 실행 루프를 구성해야합니다.

Details about run loops and examples of how to use them are provided in “Run Loops.”
실행 루프를 사용하는 방법의 예제에 대한 자세한 내용은에서 제공하는 "실행 루프."

Synchronization Tools

동기화 도구

One of the hazards of threaded programming is resource contention among multiple threads. If multiple threads try to use or modify the same resource at the same time, problems can occur. One way to alleviate the problem is to eliminate the shared resource altogether and make sure each thread has its own distinct set of resources on which to operate. When maintaining completely separate resources is not an option though, you may have to synchronize access to the resource using locks, conditions, atomic operations, and other techniques.

스레드 프로그래밍의 위험 중 하나는 여러 스레드간에 리소스 경합입니다. 여러 스레드가 동시에 같은 리소스를 사용하거나 수정하려고하면 문제가 발생할 수 있습니다.문제를 완화하는 한 가지 방법은 모두 공유 리소스를 제거하고 각 스레드가 작동 할 수있는 자원의 독특한 설정을 가지고 있는지 확인하는 것입니다. 완전히 별개의 자원을 유지하는 것이 비록 옵션이없는 경우, 당신은 자물쇠, 조건, 원자 작업 및 기타 기술을 사용하여 리소스에 대한 액세스를 동기화 할 수 있습니다.

Locks provide a brute force form of protection for code that can be executed by only one thread at a time. The most common type of lock is mutual exclusion lock, also known as a mutex. When a thread tries to acquire a mutex that is currently held by another thread, it blocks until the lock is released by the other thread. Several system frameworks provide support for mutex locks, although they are all based on the same underlying technology. In addition, Cocoa provides several variants of the mutex lock to support different types of behavior, such as recursion. For more information about the available types of locks, see “Locks.”

잠금은 한 번에 하나의 스레드에 의해 실행될 수있는 코드에 대한 보호의 무력 양식을 제공합니다. 자물쇠의 가장 일반적인 유형은 뮤텍스로 알려진 상호 배제 잠금입니다.스레드는 현재 다른 thread에 의해 보관 유지되고있는 뮤텍스를 획득하려고 할 때, 잠금 때까지이 블록은 다른 스레드에 의해 해제됩니다. 그들은 모두 동일한 기본 기술을 기반으로하지만 여러 시스템 프레임 워크, 뮤텍스 잠금에 대한 지원을 제공합니다. 또한, 코코아는 재귀 같은 행동의 다른 유형을 지원하기 위해 뮤텍스 잠금의 여러 변종을 제공합니다. 잠금 장치의 사용 가능한 형식에 대한 자세한 내용은 "잠금"을 참조하십시오.

In addition to locks, the system provides support for conditions, which ensure the proper sequencing of tasks within your application. A condition acts as a gatekeeper, blocking a given thread until the condition it represents becomes true. When that happens, the condition releases the thread and allows it to continue. The POSIX layer and Foundation framework both provide direct support for conditions. (If you use operation objects, you can configure dependencies among your operation objects to sequence the execution of tasks, which is very similar to the behavior offered by conditions.)

잠금 외에도, 시스템은 응용 프로그램 내에서 작업의 적절한 시퀀싱을 보장하는 조건에 대한 지원을 제공합니다.조건이 나타내는 조건이 참이 될 때까지 해당 스레드를 차단, 게이트 키퍼 역할을합니다. 그렇게되면, 상태는 스레드를 해제하고 ​​계속할 수 있습니다.POSIX 레이어 및 기초 프레임 워크 조건에 대한 직접적인 지원을 제공 둘. (당신은 작업 개체를 사용하는 경우, 당신은 순서에 작업 개체간에 조건에 의해 제공되는 동작과 매우 유사 작업의 실행을 종속성을 구성 할 수 있습니다.)

Although locks and conditions are very common in concurrent design, atomic operations are another way to protect and synchronize access to data. Atomic operations offer a lightweight alternative to locks in situations where you can perform mathematical or logical operations on scalar data types. Atomic operations use special hardware instructions to ensure that modifications to a variable are completed before other threads have a chance to access it.

잠금 및 조건이 동시 설계에서 매우 일반적이지만, 원자 작업은 데이터에 대한 액세스를 보호하고 동기화하는 또 다른 방법입니다. 원자 연산은 스칼라 데이터 형식에 대한 수학적 또는 논리적 연산을 수행 할 수있는 상황에서 잠금에 경량 대안을 제공합니다. 원자 작업이 다른 스레드가 액세스 할 수있는 기회를 갖기도 전에 변수에 대한 수정이 완료되는 것을 보장하기 위해 특별한 하드웨어 명령을 사용합니다.

For more information about the available synchronization tools, see “Synchronization Tools.”
사용 가능한 동기화 도구에 대한 자세한 내용은 "동기화 도구"를 참조하십시오.

Inter-thread Communication

스레드 간 통신

Although a good design minimizes the amount of required communication, at some point, communication between threads becomes necessary. (A thread’s job is to do work for your application, but if the results of that job are never used, what good is it?) Threads may need to process new job requests or report their progress to your application’s main thread. In these situations, you need a way to get information from one thread to another. Fortunately, the fact that threads share the same process space means you have lots of options for communication.

좋은 디자인은 어떤 시점에서, 필요한 통신의 양을 최소화하지만, 스레드 간의 통신이 필요하게됩니다. (스레드의 작업이 응용 프로그램에 대한 작업을 수행하는 것입니다,하지만 그 작업의 결과를 사용하지 않을 경우, 좋은 무엇입니까?) 스레드는 새 작업 요청을 처리하거나 응용 프로그램의 주 스레드에 진행 상황을보고해야 할 수도 있습니다. 이러한 상황에서는, 당신은 하나의 스레드에서 다른 정보를 얻을 수있는 방법이 필요합니다. 다행히도, 스레드가 동일한 프로세스 공간을 공유한다는 사실은 통신을위한 많은 옵션을 의미합니다.

There are many ways to communicate between threads, each with its own advantages and disadvantages. “Configuring Thread-Local Storage” lists the most common communication mechanisms you can use in OS X. (With the exception of message queues and Cocoa distributed objects, these technologies are also available in iOS.) The techniques in this table are listed in order of increasing complexity.

스레드간에 통신하는 방법에는 여러 가지, 자신의 장점과 단점이 각각 있습니다. "스레드 로컬 저장소를 구성하는 것은"당신이 OS X에서 사용할 수있는 가장 일반적인 통신 메커니즘을 나열합니다 (메시지 큐와 코코아 분산 객체를 제외하고, 이러한 기술은 또한 IOS에서 사용할 수 있습니다.)이 테이블의 기술을 순서대로 나열되어 있습니다 복잡성이 증가.

Table 1-3  Communication mechanisms

Mechanism

Description

Direct messaging

Cocoa applications support the ability to perform selectors directly on other threads. This capability means that one thread can essentially execute a method on any other thread. Because they are executed in the context of the target thread, messages sent this way are automatically serialized on that thread. For information about input sources, see “Cocoa Perform Selector Sources.”

코코아 응용 프로그램에서 직접 다른 스레드에서 선택기를 수행 할 수있는 기능을 지원합니다. 이 기능은 하나의 스레드는 기본적으로 다른 스레드에서 메서드를 실행할 수 있다는 것을 의미합니다. 그들이 대상 스레드의 컨텍스트에서 실행되기 때문에 메시지는이 방법이 자동으로 해당 스레드에 직렬화되어 전송됩니다. 입력 소스에 대한 자세한 내용은 "코코아 선택기 소스를 수행"을 참조하십시오.

Global variables, shared memory, and objects

Another simple way to communicate information between two threads is to use a global variable, shared object, or shared block of memory. Although shared variables are fast and simple, they are also more fragile than direct messaging. Shared variables must be carefully protected with locks or other synchronization mechanisms to ensure the correctness of your code. Failure to do so could lead to race conditions, corrupted data, or crashes.

두 개의 스레드 사이에서 정보를 전달하는 또 다른 간단한 방법은 전역 변수, 공유 객체, 또는 메모리의 공유 블록을 사용하는 것입니다. 공유 변수는 빠르고 간단하지만, 그들은 또한 직접 메시지보다 더 허약하다. 공유 변수는주의 깊게 코드의 정확성을 보장하기 위해 잠금이나 다른 동기화 메커니즘으로 보호해야합니다. 그렇지 않으면 경쟁 조건, 데이터 손상 또는 충돌로 이어질 수 있습니다.

Conditions

Conditions are a synchronization tool that you can use to control when a thread executes a particular portion of code. You can think of conditions as gate keepers, letting a thread run only when the stated condition is met. For information on how to use conditions, see “Using Conditions.”

상태는 스레드가 코드의 특정 부분을 실행할 때 제어하는 데 사용할 수있는 동기화 도구입니다. 당신은 명시된 조건이 충족되는 경우에만 스레드를 실행시키는 문 계원으로 조건을 생각할 수 있습니다. 조건을 사용하는 방법에 대한 자세한 내용은 "조건 사용"을 참조하십시오.

Run loop sources

A custom run loop source is one that you set up to receive application-specific messages on a thread. Because they are event driven, run loop sources put your thread to sleep automatically when there is nothing to do, which improves your thread’s efficiency. For information about run loops and run loop sources, see “Run Loops.”

사용자 정의 실행 루프 소스는 스레드에서 응용 프로그램 특정 메시지를 수신하도록 설정하는 하나입니다. 그들은 이벤트 구동 때문에, 루프 소스가 스레드의 효율성을 향상 할 수있는 것도이 없을 때 자동으로 잠자기 상태로 스레드를 넣어 실행합니다. 실행 루프에 대한 정보와 실행 루프 소스의 경우, "실행 루프"를 참조하십시오.

Ports and sockets

Port-based communication is a more elaborate way to communication between two threads, but it is also a very reliable technique. More importantly, ports and sockets can be used to communicate with external entities, such as other processes and services. For efficiency, ports are implemented using run loop sources, so your thread sleeps when there is no data waiting on the port. For information about run loops and about port-based input sources, see “Run Loops.”

포트 기반 통신은 두 개의 스레드 사이의 통신에 대한보다 정교한 방법이지만, 그것은 또한 매우 신뢰할 수있는 기술입니다. 더 중요한 것은, 포트 및 소켓과 같은 다른 프로세스와 서비스와 같은 외부 개체와 통신하는 데 사용할 수 있습니다. 효율성을 위해 포트가 실행 루프 소스를 사용하여 구현됩니다, 포트에서 대기중인 데이터가없는 때 스레드가 잠들 때문에. 실행 루프에 대한 및 포트 기반의 입력 소스에 대한 자세한 내용은 "실행 루프"를 참조하십시오.

Message queues

The legacy Multiprocessing Services defines a first-in, first-out (FIFO) queue abstraction for managing incoming and outgoing data. Although message queues are simple and convenient, they are not as efficient as some other communications techniques. For more information about how to use message queues, see Multiprocessing Services Programming Guide.

기존의 다중 서비스 수신 및 발신 데이터를 관리하기위한 선입 선출 (FIFO) 큐 추상화를 정의합니다. 메시지 큐가 간단하고 편리하지만, 그들은 다른 통신 기술로 효율적으로하지 않습니다. 메시지 큐를 사용하는 방법에 대한 자세한 내용은 다중 서비스 프로그래밍 가이드를 참조하십시오.

Cocoa distributed objects

Distributed objects is a Cocoa technology that provides a high-level implementation of port-based communications. Although it is possible to use this technology for inter-thread communication, doing so is highly discouraged because of the amount of overhead it incurs. Distributed objects is much more suitable for communicating with other processes, where the overhead of going between processes is already high. For more information, see Distributed Objects Programming Topics.

istributed 개체는 포트 기반 통신에 대한 높은 수준의 구현을 제공하는 코코아 기술입니다. 이 스레드 간 통신을 위해이 기술을 사용할 수 있지만, 이렇게하면 높은 오버 헤드 때문에 그것은 풋의 양 좋습니다. 분산 객체는 프로세스 사이가는 오버 헤드가 이미 높은 다른 프로세스와의 통신에 훨씬 더 적합합니다. 자세한 내용은 분산 객체 프로그래밍 항목을 참조하십시오.

Design Tips
디자인 팁

The following sections offer guidelines to help you implement threads in a way that ensures the correctness of your code. Some of these guidelines also offer tips for achieving better performance with your own threaded code. As with any performance tips, you should always gather relevant performance statistics before, during, and after you make changes to your code.

다음 섹션에서는 코드의 정확성을 보장하는 방식으로 스레드를 구현하는 데 도움이되는 가이드 라인을 제공합니다. 이러한 지침 중 일부는 자신의 스레드 코드와 더 나은 성능을 달성하기위한 팁을 제공합니다. 모든 성능 정보와 마찬가지로, 당신은 항상 동안, 전에 관련 성능 통계를 수집해야합니다, 당신은 당신의 코드를 변경 한 후.

Avoid Creating Threads Explicitly

명시 적으로 스레드를 생성하지 않도록

Writing thread-creation code manually is tedious and potentially error-prone and you should avoid it whenever possible. OS X and iOS provide implicit support for concurrency through other APIs. Rather than create a thread yourself, consider using asynchronous APIs, GCD, or operation objects to do the work. These technologies do the thread-related work behind the scenes for you and are guaranteed to do it correctly. In addition, technologies such as GCD and operation objects are designed to manage threads much more efficiently than your own code ever could by adjusting the number of active threads based on the current system load. For more information about GCD and operation objects, see Concurrency Programming Guide.

스레드 생성 코드를 작성 수동으로 지루한 잠재적 오류 발생 가능성이 커지므로 가능하면 당신은 그것을 피해야한다. OS X 및 IOS는 다른 API를 통해 동시성에 대한 암시 적 지원을 제공합니다.스레드를 직접 생성하는 대신, 작업을 수행하는 비동기 API를, GCD, 또는 조작 객체를 사용하는 것이 좋습니다. 이 기술은 당신을 위해 내부적으로 스레드 관련 작업을 수행하고 올바르게 수행 할 보장됩니다. 또, GCD 및 운영 객체와 같은 기술은 현재 시스템로드에 따라 활성 스레드의 수를 조정하여 훨씬 더 효율적으로 자신의 코드 어느 때보 수 스레드를 관리 할 수 ​​있도록 설계되어 있습니다. GCD 및 작업 개체에 대한 자세한 내용은 동시성 프로그래밍 가이드를 참조하십시오.

Keep Your Threads Reasonably Busy

귀하의 스레드가 합리적으로 바쁘게

If you decide to create and manage threads manually, remember that threads consume precious system resources. You should do your best to make sure that any tasks you assign to threads are reasonably long-lived and productive. At the same time, you should not be afraid to terminate threads that are spending most of their time idle. Threads use a nontrivial amount of memory, some of it wired, so releasing an idle thread not only helps reduce your application’s memory footprint, it also frees up more physical memory for other system processes to use.

만들고 수동으로 스레드를 관리하기로 결정한 경우, 스레드가 귀중한 시스템 리소스를 소비하는 기억. 당신은 당신이 스레드에 할당하는 작업을 합리적으로 긴 수명 및 생산성 있는지 확인하기 위해 최선을 다해야 할 것입니다. 동시에, 당신은 유휴 대부분의 시간을 소비하는 스레드를 종료하는 것을 두려워해서는 안됩니다. 스레드가 메모리 사소하지 않은 금액을 사용, 그것의 일부가되도록 응용 프로그램의 메모리 사용량을 줄이는 데 도움이뿐만 아니라 유휴 스레드를 해제, 유선, 또한 다른 시스템 프로세스가 사용하는 물리적 메모리를 해제합니다.

Avoid Shared Data Structures

공유 데이터 구조를 방지

The simplest and easiest way to avoid thread-related resource conflicts is to give each thread in your program its own copy of whatever data it needs. Parallel code works best when you minimize the communication and resource contention among your threads.

스레드 관련 리소스 충돌을 방지하기 위해 간단하고 쉬운 방법은 프로그램에 필요한 어떤 데이터의 복사본을 각 스레드를 제공하는 것입니다. 당신이 스레드간에 통신 및 리소스 경합을 최소화 할 때 병렬 코드를 가장 잘 작동합니다.

Creating a multithreaded application is hard. Even if you are very careful and lock shared data structures at all the right junctures in your code, your code may still be semantically unsafe. For example, your code could run into problems if it expected shared data structures to be modified in a specific order. Changing your code to a transaction-based model to compensate could subsequently negate the performance advantage of having multiple threads. Eliminating the resource contention in the first place often results in a simpler design with excellent performance.

다중 스레드 응용 프로그램을 작성하는 것은 어렵습니다. 당신은 코드의 모든 권리 고비 매우 신중하고 잠금 공유 데이터 구조 인 경우에도, 귀하의 코드는 여전히 의미가 안전하지 않을 수 있습니다. 이 특정 순서로 수정할 수있는 공유 데이터 구조를 예상하는 경우 예를 들어, 코드는 문제에 실행할 수 있습니다. 보상하는 트랜잭션 기반 모델에 코드를 변경하면 이후 여러 스레드를 갖는 성능상의 이점을 무효화 할 수 있습니다. 처음에 자원 경합을 제거하면 종종 우수한 성능을 가진 단순한 설계 결과.

Threads and Your User Interface

스레드와 사용자 인터페이스

If your application has a graphical user interface, it is recommended that you receive user-related events and initiate interface updates from your application’s main thread. This approach helps avoid synchronization issues associated with handling user events and drawing window content. Some frameworks, such as Cocoa, generally require this behavior, but even for those that do not, keeping this behavior on the main thread has the advantage of simplifying the logic for managing your user interface.

응용 프로그램이 그래픽 사용자 인터페이스를 가지고 있다면, 그것은 당신이 사용자 관련 이벤트를 수신하고 응용 프로그램의 주 스레드에서 인터페이스 업데이트를 시작하는 것이 좋습니다. 이 방법은 사용자 이벤트를 처리하고 윈도우 내용을 도면과 관련된 동기화 문제를 방지하는 데 도움이됩니다. 같은 코코아와 같은 일부 프레임 워크, 일반적으로이 동작을 필요로하지만, 심지어는 주 스레드에서이 동작을 유지하지 않는 사람들을 위해 사용자 인터페이스를 관리하기위한 논리를 단순화의 이점이있다.

There are a few notable exceptions where it is advantageous to perform graphical operations from other threads. For example, you can use secondary threads to create and process images and perform other image-related calculations. Using secondary threads for these operations can greatly increase performance. If you are not sure about a particular graphical operation though, plan on doing it from your main thread.

그것은 다른 스레드에서 그래픽 작업을 수행 할 유리한 몇 가지 주목할만한 예외가 있습니다. 예를 들어, 생성하고 처리하는 이미지 및 기타 이미지 관련 계산을 수행 할 보조 스레드를 사용할 수 있습니다. 이러한 작업을 위해 보조 스레드를 사용하여 성능을 크게 향상시킬 수 있습니다. 당신은 당신의 주 스레드에서 수행하는 방법에 대한 계획,하지만 특정 그래픽 작업에 대한 확실하지 않은 경우.

For more information about Cocoa thread safety, see “Thread Safety Summary.” For more information about drawing in Cocoa, see Cocoa Drawing Guide.

코코아 스레드 안전에 대한 자세한 내용은 코코아 그리기에 대한 자세한 내용은 "스레드 안전 요약"을 참조하십시오., 코코아 드로잉 설명서를 참조하십시오.

Be Aware of Thread Behaviors at Quit Time

Quit (종료) 시간에 스레드 동작을 인식

A process runs until all non-detached threads have exited. By default, only the application’s main thread is created as non-detached, but you can create other threads that way as well. When the user quits an application, it is usually considered appropriate behavior to terminate all detached threads immediately, because the work done by detached threads is considered optional. If your application is using background threads to save data to disk or do other critical work, however, you may want to create those threads as non-detached to prevent the loss of data when the application exits.

모든 비 분리 된 스레드가 종료 될 때까지 프로세스가 실행됩니다. 기본적으로 응용 프로그램의 주 스레드가 아닌 분리로 만들어집니다,하지만 당신은뿐만 아니라 다른 스레드에게 그 방법을 만들 수 있습니다. 분리 된 스레드에 의해 수행 작업이 선택적으로 간주되기 때문에 사용자가 응용 프로그램을 종료 할 때 일반적으로, 즉시 모든 분리 된 스레드를 종료하는 적절한 행동으로 간주됩니다. 응용 프로그램이 다른 중요한 작업을 디스크에 데이터를 저장하거나 수행하는 백그라운드 스레드를 사용하는 경우, 그러나, 당신은 데이터 손실 응용 프로그램이 종료되지 않도록 비 분리로 해당 스레드를 만들 수 있습니다.

Creating threads as non-detached (also known as joinable) requires extra work on your part. Because most high-level thread technologies do not create joinable threads by default, you may have to use the POSIX API to create your thread. In addition, you must add code to your application’s main thread to join with the non-detached threads when they do finally exit. For information on creating joinable threads, see “Setting the Detached State of a Thread.”

(또한 조인이라고도 함) 비 분리로 작성 스레드 부분에 추가 작업이 필요합니다. 가장 높은 수준의 스레드 기술은 기본적으로 조인 스레드를 생성하지 않기 때문에, 당신은 당신의 스레드를 생성하는 POSIX API를 사용 할 수 있습니다. 또한, 당신은 그들이 마지막으로 종료 않는 경우가 아닌 분리 된 스레드를 결합하는 응용 프로그램의 주 스레드에 코드를 추가해야합니다. 결합 가능한 스레드를 만드는 방법에 대한 자세한 내용은 "스레드의 분리 상태 설정"을 참조하십시오.

If you are writing a Cocoa application, you can also use the applicationShouldTerminate: delegate method to delay the termination of the application until a later time or cancel it altogether. When delaying termination, your application would need to wait until any critical threads have finished their tasks and then invoke the replyToApplicationShouldTerminate: method. For more information on these methods, see NSApplication Class Reference.

당신은 코코아 응용 프로그램을 작성하는 경우, 당신은 또한 applicationShouldTerminate을 사용할 수 있습니다 : 대리자 메서드를 나중에까지 응용 프로그램의 종료를 지연 또는 전부를 취소 할 수 있습니다. 방법 : 종료를 지연하는 경우, 응용 프로그램은 중요한 스레드가 작업을 완료 한 후 replyToApplicationShouldTerminate를 호출 할 때까지 대기해야합니다. 이러한 메서드에 대한 자세한 내용은 NSApplication 클래스 참조를 참조하십시오.

Handle Exceptions

예외 처리

Exception handling mechanisms rely on the current call stack to perform any necessary clean up when an exception is thrown. Because each thread has its own call stack, each thread is therefore responsible for catching its own exceptions. Failing to catch an exception in a secondary thread is the same as failing to catch an exception in your main thread: the owning process is terminated. You cannot throw an uncaught exception to a different thread for processing.

예외 처리 메커니즘은 예외가 throw 될 때 모든 필요한 정리를 수행 할 현재 호출 스택에 의존하고 있습니다. 각 스레드가 자신의 호출 스택을 가지고 있기 때문에, 각 스레드는 자신의 예외를 잡는 따라서 책임이 있습니다.소유하는 프로세스가 종료됩니다 : 보조 스레드에서 예외를 catch하는 데 실패하면 기본 스레드에서 예외를 catch하지 못하는 것과 동일합니다. 당신은 처리를 위해 다른 스레드에 캐치되지 않는 예외를 throw 할 수 없습니다.

If you need to notify another thread (such as the main thread) of an exceptional situation in the current thread, you should catch the exception and simply send a message to the other thread indicating what happened. Depending on your model and what you are trying to do, the thread that caught the exception can then continue processing (if that is possible), wait for instructions, or simply exit.

현재 스레드에서 예외 상황을 다른 스레드 (예 : 주 스레드)를 통보해야하는 경우, 당신은 예외를 catch하고 단순히 무슨 일이 있었는지 나타내는 다른 스레드에 메시지를 보내야합니다. 모델과 실행하려고에 따라 예외를 잡은 쓰레드가 그 (즉, 가능한 경우) 처리를 계속할 수 있습니다 지침을 기다리거나 단순히 종료합니다.

In some cases, an exception handler may be created for you automatically. For example, the @synchronized directive in Objective-C contains an implicit exception handler.

어떤 경우에는, 예외 핸들러가 자동으로 생성 할 수 있습니다. 예를 들어, 오브젝티브-C에서 @ 동기화 지시어는 암시 적 예외 처리기가 포함되어 있습니다.

Terminate Your Threads Cleanly

깔끔하게 스레드 종료

The best way for a thread to exit is naturally, by letting it reach the end of its main entry point routine. Although there are functions to terminate threads immediately, those functions should be used only as a last resort. Terminating a thread before it has reached its natural end point prevents the thread from cleaning up after itself. If the thread has allocated memory, opened a file, or acquired other types of resources, your code may be unable to reclaim those resources, resulting in memory leaks or other potential problems.

종료 스레드 가장 좋은 방법은 그것의 주 진입 점 루틴의 끝에 도달시키는 것으로, 자연스럽게. 바로 스레드를 종료하는 기능이 있지만, 그 기능은 최후의 수단으로 만 사용해야합니다. 그것의 자연 종점 자체 후 청소에서 스레드를 방지 도달하기 전에 스레드 종료.스레드가 메모리를 할당 한 경우, 파일을 열거 나 다른 유형의 리소스를 인수 코드는 메모리 누수 또는 기타 잠재적 인 문제가 발생, 그 자원을 재생하지 못할 수 있습니다.

For more information on the proper way to exit a thread, see “Terminating a Thread.”
스레드를 종료하는 적절한 방법에 대한 자세한 내용은 "스레드 종료"를 참조하십시오.

Thread Safety in Libraries

라이브러리에서 스레드로부터의 안전성

Although an application developer has control over whether an application executes with multiple threads, library developers do not. When developing libraries, you must assume that the calling application is multithreaded or could switch to being multithreaded at any time. As a result, you should always use locks for critical sections of code.

응용 프로그램 개발자가 응용 프로그램이 여러 스레드 실행 여부를 제어 할 있지만, 라이브러리 개발자는하지 않습니다. 라이브러리를 개발할 때, 당신은 호출 응용 프로그램이 다중 스레드 언제든지 멀티 스레드 인으로 전환 할 수 있다고 가정해야합니다.그 결과로, 당신은 항상 코드의 임계 영역에 대한 잠금을 사용해야합니다.

For library developers, it is unwise to create locks only when an application becomes multithreaded. If you need to lock your code at some point, create the lock object early in the use of your library, preferably in some sort of explicit call to initialize the library. Although you could also use a static library initialization function to create such locks, try to do so only when there is no other way. Execution of an initialization function adds to the time required to load your library and could adversely affect performance.

라이브러리 개발자를 들어, 응용 프로그램이 멀티 스레드가되고있는 경우에만 잠금을 생성하는 것은 현명합니다. 당신은 어떤 지점에서 코드를 잠글 필요하면 바람직 라이브러리를 초기화하는 명시적인 호출의 일종으로, 초기 라이브러리의 사용 잠금 개체를 만듭니다. 당신은 또한 잠금을 생성하는 정적 라이브러리 초기화 함수를 사용할 수 있지만, 다른 방법이없는 경우에만 그렇게하려고합니다.초기화 함수의 실행은 라이브러리를로드하고 성능에 부정적인 영향을 미칠 수있는 필요한 시간을 추가합니다.

If you are developing a Cocoa library, you can register as an observer for the NSWillBecomeMultiThreadedNotification if you want to be notified when the application becomes multithreaded. You should not rely on receiving this notification, though, as it might be dispatched before your library code is ever called.

당신은 코코아 라이브러리를 개발하는 경우 응용 프로그램이 다중 스레드 될 때 통지하려는 경우, 당신은 NSWillBecomeMultiThreadedNotification에 대한 관찰자로 등록 할 수 있습니다. 라이브러리 코드가 적 호출되기 전에가 전달 될 수도로서 당신은,하지만,이 알림 수신에 의존해서는 안됩니다.

Posted by 창업자닉군
,