Linux C++ 多线程编程实例

本文详细介绍了在Linux系统中使用POSIX线程接口(pthread)创建线程的基本步骤,包括线程创建函数pthread_create的用法,如何向线程传递参数,线程终止的机制,以及线程标识的获取。通过实例演示了线程同步的必要性和pthread_join的作用。
摘要由CSDN通过智能技术生成

Linux系统下的多线程遵循POSIX线程接口,称为 pthread。编写Linux下的多线程程序,需要使用头文件pthread.h,连接时需要使用库libpthread.a。顺便说一下,Linux 下pthread的实现是通过系统调用clone()来实现的。clone()是 Linux所特有的系统调用,它的使用方式类似fork。

1、线程创建

pthread_create

int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict attr, void *(*start_rtn)(void),void *restrict arg);

restrict 修饰的指针: 由 restrict 修饰的指针是最初唯一对指针所指向的对象进行存取的方法,仅当第二个指针基于第一个时,才能对对象进行存取。对对象的存取都限定于基于由 restrict 修饰的指针表达式中。 由 restrict 修饰的指针主要用于函数形参,或指向由 malloc() 分配的内存空间。restrict 数据类型不改变程序的语义。 编译器能通过作出 restrict 修饰的指针是存取对象的唯一方法的假设,更好地优化某些类型的例程。

返回值:若是成功建立线程返回0,否则返回错误的编号
形式参数:
pthread_t *restrict tidp 要创建的线程的线程id指针
const pthread_attr_t restrict attr 创建线程时的线程属性
void
(start_rtn)(void) 返回值是void类型的指针函数
void *restrict arg start_rtn的行参

创建一个简单线程

#include<iostream>
#include<pthread.h>
#include<unistd.h>

using namespace std;

void * thread1(void*)
{
    for(int i=0; i<10; i++)
    {
        cout << "thread1"<< endl;
        sleep(1);
    }
}

void * thread2(void*)
{
    for(int i=0; i<10; i++)
    {
        cout << "thread2" << endl;
        sleep(1);
    }
}

int main(int argc, char * argv[])
{
    int ret = 0;
    pthread_t id1, id2;

    ret = pthread_create(&id1, NULL, thread1, NULL);
    if(ret)
    {
        cout << "create thread1 failed ret:" << ret << endl;
    }

    ret = pthread_create(&id2, NULL, thread2, NULL);
    if(ret)
    {
        cout << "create thread2 failed ret"<< ret << endl;
    }

    pthread_join(id1, NULL);
    pthread_join(id2, NULL);

    cout << "end" << endl;

    return 0;
}

执行结果两个线程交替执行

[admin@admin pthread]$ ./a.out 
thread1
thread2
thread1
thread2
thread1
thread2
thread1
thread2
thread1
thread2
end

向线程传递参数整形和结构体

#include<iostream>
#include<pthread.h>
#include<unistd.h>

using namespace std;

struct ThreadParam
{
    int data;
    char *str;
};

void * thread1(void * arg)
{
    int * data;
    data = (int *)arg;
    cout << "data:"<< *data << endl;

    return (void*)0;
}

void * thread2(void * arg)
{
    ThreadParam* param;
    param = (ThreadParam*)arg;
    cout << "data:" << param->data << " str:" << param->str << endl;

    return (void*)0;
}

int main(int argc, char * argv[])
{
    int ret = 0;

    pthread_t id1;
    pthread_t id2;

    int test = 4;
    int *attr = &test;


    ThreadParam param;
    param.data = 1;
    param.str = "abcd";

    ret = pthread_create(&id1, NULL, thread1, (void*)attr);

    if(ret)
    {
        cout << "create thread1 failded ret:" << ret << endl;
    }

    ret = pthread_create(&id2, NULL, thread2, (void*)&param);

    if(ret)
    {
        cout << "create thread2 failded ret:" << ret << endl;
    }

    pthread_join(id1, NULL);
    pthread_join(id2, NULL);
}

执行结果

[admin@admin pthread]$ ./a.out 
data:4
data:1 str:abcd

2、线程的终止

如果进程中任何一个线程中调用exit,_Exit,或者是_exit,那么整个进程就会终止,
与此类似,如果信号的默认的动作是终止进程,那么,把该信号发送到线程会终止进程。
线程的正常退出的方式:
(1) 线程只是从启动例程中返回,返回值是线程中的退出码
(2) 线程可以被另一个进程进行终止
(3) 线程自己调用pthread_exit函数

两个重要的函数原型:

pthread_exit

void pthread_exit(void *rval_ptr);
/rval_ptr 线程退出返回的指针/

pthread_join

int pthread_join(pthread_t thread,void **rval_ptr);
/成功结束进程为0,否则为错误编码/

pthread_join使一个线程等待另一个线程结束。
代码中如果没有pthread_join主线程会很快结束从而使整个进程结束,从而使创建的线程没有机会开始执行就结束了。加入pthread_join后,主线程会一直等待直到等待的线程结束自己才结束,使创建的线程有机会执行。
头文件 : #include <pthread.h>
函数定义: int pthread_join(pthread_t thread, void **retval);
描述 :pthread_join()函数,以阻塞的方式等待thread指定的线程结束。当函数返回时,被等待线程的资源被收回。如果线程已经结束,那么该函数会立即返回。并且thread指定的线程必须是joinable的。
参数 :thread: 线程标识符,即线程ID,标识唯一线程。retval: 用户定义的指针,用来存储被等待线程的返回值。
返回值 : 0代表成功。 失败,返回的则是错误号。

线程正常退出

#include<iostream>
#include<pthread.h>
#include<unistd.h>

using namespace std;

void * thread(void * arg)
{
    for(int i=0; i<10; i++)
    {
        cout <<"thread i:"<< i << endl;

        if(i==5)
        {
            pthread_exit(0);
        }

        sleep(1);
    }
}

int main(int argc, char * argv[])
{
    int ret = 0;
    
    pthread_t id1;

    ret = pthread_create(&id1, NULL, thread, NULL);

    if(ret)
    {
        cout << "create thread failed" << endl;
    }

    pthread_join(id1, NULL);

    cout << "end" << endl;
}

执行结果

[admin@admin pthread]$ ./a.out 
thread i:0
thread i:1
thread i:2
thread i:3
thread i:4
thread i:5
end

线程结束并返回一个复杂的数据结构

#include<iostream>
#include<pthread.h>
#include<unistd.h>

using namespace std;

struct TheadParam
{
    int data;
    char *str;
};

void * thread(void * arg)
{
    TheadParam * param = new TheadParam;
    param->data = 1;
    param->str = "abcd";

    return (void*)param;
}

int main(int argc, char * argv[])
{
    int ret = 0;

    pthread_t id1;

    void *p;

    TheadParam* param;

    ret = pthread_create(&id1, NULL, thread, NULL);

    if(ret)
    {
        cout << "create thread failed ret:" << ret << endl;
    }

    pthread_join(id1, &p);

    param = (TheadParam*)p;

    delete p;

    cout << "data:" << param->data << " str:" << param->str << endl;
}

执行结果

[admin@admin pthread]$ ./a.out 
data:0 str:abcd

3、线程标识
函数原型:

pthread_self

pthread_t pthread_self(void);
获得线程自身的ID

getpid

pid_t getpid(void);
取得进程识别码

#include<iostream>
#include<pthread.h>
#include<unistd.h>

using namespace std;

void * thread(void * arg)
{
    pthread_t tid = pthread_self();

    cout << "tid:" << tid << endl;

    sleep(1);

    return (void*)0;
}

int main(int argc, char * argv[])
{
    int ret = 0;

    pthread_t id1;

    ret = pthread_create(&id1, NULL, thread, NULL);

    if(ret)
    {
        cout << "create thread failed ret:" << ret << endl;
    }

    pthread_join(id1, NULL);

    pthread_t tid = pthread_self();
    pid_t pid = getpid();

    cout << "tid:" << tid << " pid:" << pid << endl;
}

执行结果

[admin@admin pthread]$ ./a.out 
tid:140010420446976
tid:140010437293888 pid:8953

后面的文章介绍线程同步的四种方式

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Linux C多线程编程是指在Linux系统下使用C语言进行多线程编程的实践。多线程编程的目的在于提高程序的效率,增强程序的并发性和响应性。下面举个实例说明多线程编程的应用。 假设有一个简单的程序需要处理大量的文本数据,要求计算文本中出现某个关键字的次数,并将结果输出到文件中。如果采用单线程方式来实现,可能会因为数据量过大而导致程序运行缓慢,甚至崩溃。而采用多线程方式,可以将数据分成多个块,分别进行关键字统计和输出操作,从而提高程序的效率和响应速度。 实现多线程编程的关键在于线程之间的同步和互斥。我们可以使用pthread库提供的函数来实现线程的创建、销毁、同步和互斥。pthread_create()函数用于创建新的线程,pthread_join()函数用于等待线程结束并获取其返回值。pthread_mutex_init()函数和pthread_mutex_lock()、pthread_mutex_unlock()函数用于实现线程之间的互斥。通过使用这些函数,我们可以在程序中实现多线程编程。 在实际应用多线程编程时,我们需要注意以下几点:首先,要根据实际情况设置合适的线程数以避免资源的浪费和线程的阻塞;其次,要注意线程之间的同步和互斥,避免出现竞争条件和死锁等问题;最后,要注意内存管理和异常处理等问题,保证程序的稳定性和可靠性。 综上所述,Linux C多线程编程是提高程序效率和响应速度的有效手段,并需要注意线程之间的同步和互斥问题。在实践中,我们需要结合实际应用情况合理设置线程数,处理好同步和互斥问题,并注意内存管理和异常处理等问题,以保证程序的稳定性和可靠性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值