c ++多线程_C ++中的多线程

本文介绍了C++中的多线程概念,包括线程的创建、连接和分离。多线程能实现资源的更好利用和程序设计的简化,提高响应速度。在Linux环境下,线程函数在<pthread.h>头文件中声明。文中通过示例展示了如何使用pthread_create创建线程,以及pthread_join和pthread_detach函数的用法。
摘要由CSDN通过智能技术生成

c ++多线程

Multithreading means two or more threads running concurrently where each thread is handling a different task. When you login to you Facebook profile, on your news feed, you can see live videos, you can comment or hit a like button, everything simultaneously. This is the best example of multithreading. Multithreading environment allows you to run many activities simultaneously; where different threads are responsible for different activities.

多线程是指两个或多个同时运行的线程,其中每个线程处理不同的任务。 当您登录Facebook个人资料时,在新闻供稿上,您可以看到实时视频,可以发表评论或按“赞”按钮,所有这些都可以同时进行。 这是多线程的最佳示例。 多线程环境允许您同时运行许多活动。 不同的线程负责不同的活动。

There are various uses of Multithreading, some of them are:

多线程有多种用途,其中一些是:

  • Better resource utilization.

    更好地利用资源。

  • Simpler program design.

    程序设计更简单。

  • More responsive programs.

    响应速度更快的程序。

什么是线程? (What is a Thread?)

Thread is generally referred as a light weight process. Each thread executes different parts of a program. Each thread shares memory, file descriptors and other system resources. In Linux, all thread functions are declared in <pthread.h> header file. But it is not available in standard C++ library.

线程通常被称为轻量级进程。 每个线程执行程序的不同部分。 每个线程共享内存,文件描述符和其他系统资源。 在Linux中,所有线程函数都在<pthread.h>头文件中声明。 但是它在标准C ++库中不可用。

在Linux(C ++)中创建线程 (Creating Threads in Linux(C++))

  1. pthread_create(): It creates a new thread. Below is the syntax:

    pthread_create() :它创建一个新线程。 语法如下:

    pthread_create(threadID, attr, start_routine, arg)

    In the code above:

    在上面的代码中:

    threadID: Is a unique identifier for each thread. ThreadID of threads are compared using pthread_equal() function.

    threadID :是每个线程的唯一标识符。 使用pthread_equal()函数比较线程的ThreadID。

    attr: Attribute object that may be used to set various thread attributes. It controls interaction of thread with rest of the program.

    attr :可用于设置各种线程属性的属性对象。 它控制线程与程序其余部分的交互。

    start_routine: The C++ routine that the thread will execute once it is created.

    start_routine :创建线程后将执行的C ++例程。

    arg: Single argument must be passed by reference as a pointer of type void. If no argument is to be passed, null can be used.

    arg :单个参数必须作为空类型的指针通过引用传递。 如果不传递任何参数,则可以使用null。

  2. pthread_exit(): It is used to terminate any thread.

    pthread_exit() :用于终止任何线程。

Below is a simple program on creating threads in C++:

下面是一个使用C ++创建线程的简单程序:

#include <iostream>
#include <pthread.h>
using namespace std;

char* str = "Child thread";

void* func(void *str)
{
    cout << "Child thread Created: " << (char*)str;
}
// main function
int main()
{
    s = ctime(&Time);
    // Step 1: Declaring thread
    pthread_t t;    
    // Step 2: Calling create thread function
    pthread_create(&t, NULL, &func, (void*)str); 
    /*
        Syntax for pthread_create is:
        pthread_create(threadID,attr,start_routine,arg)
        Here,
        threadID = t, arg = (void*)str, atrr = Null, start_routine = func
    */
    cout << "Main thread created" << endl;
    pthread_join(t, NULL);
    //Exiting after completion
    exit(EXIT_SUCCESS); 
    return 0;
}

Main thread created Child thread created: Child thread

已创建主线程已创建子线程:子线程

连接和分离线程 (Joining and Detaching Threads)

There are two methods which we can use to join or detach threads:

我们可以使用两种方法来连接或分离线程:

join()函数 (join() function)

Joining of a thread is done by using the join() function of the thread class. It makes main thread and child thread inter dependent. Main thread terminates only after child thread terminates i.e. main thread waits for child thread to complete execution.

线程的连接是通过使用线程类的join()函数完成的。 它使主线程和子线程相互依赖。 主线程仅在子线程终止后终止,即主线程等待子线程完成执行。

Syntax:

句法:

threadname.join();

It returns once all functions are completed. A thread is not joinable when it is assigned to another thread or when join() or detach() is called.

一旦所有功能完成,它将返回。 当一个线程分配给另一个线程或调用join()detach()时,该线程不可连接。

Syntax:

句法:

/* 
    It checks whether a thread is joinable. 
    It returns bool value.
*/
threadname.joinable();

detach()函数 (detach() function)

The detach() function detaches a thread from the parent thread. It allows both main thread and child thread to execute independently.

detach()函数从父线程分离线程。 它允许主线程和子线程独立执行。

Syntax:

句法:

threadname.detach();

使用join()方法的程序示例 (Program Example for using join() method)

Let's have a simple example to demonstrate the use of join() function to join two threads:

让我们用一个简单的示例来演示如何使用join()函数来连接两个线程:

#include <iostream>
#include <unistd.h>   // To include sleep function
#include<ctime>   // To get system time
#include <pthread.h>
using namespace std;

string s;
time_t Time = time(0);

void* func(void*)
{
    s = ctime(&Time);
    sleep(1);   //C alls sleep function
    cout << "Child thread Created " << s << endl;
}

// main function
int main()
{
    s = ctime(&Time);
    //Step 1: Declaring thread
    pthread_t t1[5];
    for(int i=0; i<5; i++)
    {
        cout << "Thread T[" << i << "] is Created " << s << endl;
        // Step 2: calling create thread function
        pthread_create(&t1[i], NULL, &func, NULL); 
        // Joining threads, main thread waits for child thread to complete
        pthread_join(t1[i], NULL); 
}
//Exiting after completion
exit(EXIT_SUCCESS); 
return 0;
}

Thread T[0] is Created Wed Nov 1 02:30:57 2017 Child thread Created Wed 1 02:30:57 2017] Thread T[1] is Created Wed Nov 1 02:30:57 2017 Child thread Created Wed 1 02:30:57 2017 Thread T[2] is Created Wed Nov 1 02:30:57 2017 Child thread Created Wed 1 02:30:57 2017 Thread T[3] is Created Wed Nov 1 02:30:57 2017 Child thread Created Wed 1 02:30:57 2017 Thread T[4] is Created Wed Nov 1 02:30:57 2017 Child thread Created Wed 1 02:30:57 2017

线程T [0]已创建于11月1日星期三02:30:57 2017子线程已创建Wed 1 02:30:57 2017]线程T [1]已创建于2017年11月1日星期三02:30:57子线程已创建星期三1 02 :30:57 2017年11月1日星期三创建线程T [2] 2017年3月1日星期三创建子线程2017年11月1日星期三02:30:57创建线程2017年11月1日星期三创建线程T [3]已创建星期三1 02:30:57 2017线程T [4]已创建星期三十一月1 02:30:57 2017子线程已创建星期三2017 2:30:57

使用detach()方法的程序示例 (Program Example for using detach() method)

Let's have a simple example to demonstrate the use of join() function to detach two threads:

让我们用一个简单的示例来演示如何使用join()函数分离两个线程:

#include <iostream>
#include <unistd.h>   // To include sleep function
#include<ctime>   // To get system time
#include <pthread.h>
using namespace std;

string s;
time_t Time = time(0);

void* func(void*)
{
    s = ctime(&Time);
    sleep(1);   // Calls sleep function
    cout << "Child thread Created " << s << endl;
}

// main function
int main()
{
    s = ctime(&Time);
    // Step 1: Declaring thread
    pthread_t t1[5]; 
    for(int i=0; i<5; i++)
    {
        cout << "Thread T[" << i << "] is Created " << s << endl;
        // Step 2: Calling create thread function
        pthread_create(&t1[i], NULL, &func, NULL); 
        // Step 3: main thread doesn't waits for child thread to complete
        pthread_detach(t1[i]); 
}
// Exiting after completion
exit(EXIT_SUCCESS); 
return 0;
}

Thread T[0] is Created Wed Nov 1 02:38:14 2017 Thread T[1] is Created Wed Nov 1 02:38:14 2017 Thread T[2] is Created Wed Nov 1 02:38:14 2017 Thread T[3] is Created Wed Nov 1 02:38:14 2017 Thread T[4] is Created Wed Nov 1 02:38:14 2017

线程T [0]创建于2017年11月1日星期三02:38:14 2017线程T [1]创建于2017年11月1日星期三02:38:14线程T [2]创建于2017年11月1日星期三02:38:14 [3]创建于2017年11月1日星期三02:38:14线程T [4]创建于2017年11月1日星期三02:38:14

Hoope you have understood the concept of thread creation in C++.

哎呀,您已经了解C ++中线程创建的概念。

翻译自: https://www.studytonight.com/cpp/multithreading-in-cpp.php

c ++多线程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值