Espacios de nombres
Variantes
Acciones

std::thread::thread

De cppreference.com
< cpp‎ | thread‎ | thread
 
 
Tema Biblioteca de ayuda
Threads
Original:
Threads
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
thread(C++11)
this_thread espacio de nombres
Original:
this_thread namespace
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
get_id(C++11)
yield(C++11)
sleep_for(C++11)
sleep_until(C++11)
Exclusión mutua
Original:
Mutual exclusion
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
mutex(C++11)
timed_mutex(C++11)
Gestión de bloqueos genérico
Original:
Generic lock management
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
lock_guard(C++11)
unique_lock(C++11)
defer_lock_t
try_to_lock_t
adopt_lock_t
(C++11)
(C++11)
(C++11)
lock(C++11)
try_lock(C++11)
defer_lock
try_to_lock
adopt_lock
(C++11)
(C++11)
(C++11)
Las variables de condición
Original:
Condition variables
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
condition_variable(C++11)
condition_variable_any(C++11)
notify_all_at_thread_exit(C++11)
cv_status(C++11)
Futuros
Original:
Futures
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
promise(C++11)
future(C++11)
shared_future(C++11)
packaged_task(C++11)
async(C++11)
launch(C++11)
future_status(C++11)
future_error(C++11)
future_category(C++11)
future_errc(C++11)
 
std::thread
Clases de miembros
Original:
Member classes
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
thread::id
Las funciones miembro
Original:
Member functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
thread::thread
thread::~thread
thread::operator=
Los observadores
Original:
Observers
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
thread::joinable
thread::get_id
thread::native_handle
thread::hardware_concurrency
Operaciones
Original:
Operations
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
thread::join
thread::detach
thread::swap
Terceros funciones
Original:
Non-member functions
The text has been machine-translated via Google Translate.
You can help to correct and verify the translation. Click here for instructions.
std::swap
 
thread();
(1) (desde C++11)
thread( thread&& other );
(2) (desde C++11)
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
(3) (desde C++11)
thread(const thread&) = delete;
(4) (desde C++11)

Construye un nuevo objeto Thread .

1) Crea un objeto nuevo que no representa a ningún hilo .
2) Move constructor. Construye el objeto Thread para representar el hilo de ejecución que estaba representado por other. Después de esta llamada other
3) Crea un nuevo objeto std::thread y la asocia con un hilo en ejecución. Primero, el constructor copia todos args... los argumentos para el almacenamiento local del nuevo hilo:
template <class T>
typename decay<T>::type decay_copy(T&& v) {
    return std::forward<T>(v);
}
Las excepciones producidas durante la evaluación y la copia de los argumentos se lanzan en el hilo actual, no el nuevo hilo .
El código que se ejecutará en el nuevo hilo se define de la siguiente manera. Vamos a referirnos a Nonecopied_args como t1, t2, ..., tN, donde N es
sizeof...(copied_args)and copied_args is the result of calling decay_copy as defined above. The following code will be run in the new thread:
  • Si f es un puntero a una función miembro de T clase, entonces se le llama. El valor de retorno es ignorado. Efectivamente, el código se ejecuta la siguiente:
    Original:
    If f is pointer to a member function of class T, then it is called. The return value is ignored. Effectively, the following code is executed:
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • (t1.*f)(t2, ..., tN) si el tipo de t1 es o bien T, la referencia a T o referencia a tipo derivado de T .
    Original:
    (t1.*f)(t2, ..., tN) if the type of t1 is either T, reference to T or reference to type derived from T.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • ((*t1).*f)(t2, ..., tN) de otra manera .
    Original:
    ((*t1).*f)(t2, ..., tN) otherwise.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • Si N == 1 y f es puntero a un objeto de miembro de datos de una clase, a continuación, se accede a ella. El valor del objeto se ignora. Efectivamente, el código se ejecuta la siguiente:
    Original:
    If N == 1 and f is pointer to a member data object of a class, then it is accessed. The value of the object is ignored. Effectively, the following code is executed:
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • t1.*f si y el tipo de t1 es o bien T, la referencia a T o referencia a tipo derivado de T .
    Original:
    t1.*f if and the type of t1 is either T, reference to T or reference to type derived from T.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • (*t1).*f de otra manera .
    Original:
    (*t1).*f otherwise.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
  • f se llama como un puntero a una función no miembro en los demás casos. El valor de retorno es ignorado. Efectivamente, f(t1, t2, ..., tN) se ejecuta .
    Original:
    f is called as a pointer to a non-member function in all other cases. The return value is ignored. Effectively, f(t1, t2, ..., tN) is executed.
    The text has been machine-translated via Google Translate.
    You can help to correct and verify the translation. Click here for instructions.
4) Thread no es copiable. No hay dos std::thread objetos que pueden representar al mismo hilo de ejecución .

Contenido

[editar] Parámetros

other - otro objeto hilo para construir este objeto con hilo
f - funcionar a ejecutar en el nuevo hilo
args... - argumentos que se pasan a la nueva función

[editar] Excepciones

1-2)
noexcept specification:  
noexcept
  (desde C++11)
3) std::system_error si el hilo no se pudo iniciar. La excepción puede representar la std::errc::resource_unavailable_try_again condición de error u otra condición de error específico de la implementación .

[editar] Notas

Los argumentos de la función del hilo se copian por valor. Si se quiere pasar un argumento por referencia a la función del hilo, tiene que ser envuelto (por ejemplo, con std::ref o std::cref) .

Cualquier valor de retorno de la función es ignorada. Si la función lanza una excepción, std::terminate se llama. Para pasar valores de retorno o excepciones al subproceso de llamada, o std::promise std::async se puede usar .

[editar] Ejemplo

#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>
 
void f1(int n)
{
    for(int i=0; i<5; ++i) {
        std::cout << "Thread " << n << " executing\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}
 
void f2(int& n)
{
    for(int i=0; i<5; ++i) {
        std::cout << "Thread 2 executing\n";
        ++n;
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
}
 
int main()
{
    int n = 0;
    std::thread t1; // t1 is not a thread
    std::thread t2(f1, n+1); // pass by value
    std::thread t3(f2, std::ref(n)); // pass by reference
    std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread
    t2.join();
    t4.join();
    std::cout << "Final value of n is " << n << '\n';
}

Possible output:

Thread 1 executing
Thread 2 executing
Thread 1 executing
Thread 2 executing
Thread 1 executing
Thread 2 executing
Thread 1 executing
Thread 2 executing
Thread 1 executing
Thread 2 executing
Final value of n is 5