线程

c++11之前,c++中并没有标准的线程库,一般用的是pthread库。pthread的一个简单例子如下:

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

using namespace std;

#define MAX_NUM 5

void *say_hello(void *args) //线程回调函数
{
    int *tmp = (int *)args;

    cout << "hello thread:" << *tmp << endl;
    return 0;
}

int main()
{
    pthread_t tids[MAX_NUM];
    int index[MAX_NUM];
    pthread_attr_t attr;
    void *status;

    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);//设置为可连接

    for (int i = 0; i < MAX_NUM; i++) {
        cout << "create thread:" << i + 1 << endl;
        index[i] = i + 1;
        int ret = pthread_create(&tids[i], NULL, say_hello, (void *)&index[i]);
        if (ret != 0) {
            cout << "create thread error:" << ret << endl;
        }   
    }   

    pthread_attr_destroy(&attr);
    for (int i = 0; i < MAX_NUM; i++) {
        int rc = pthread_join(tids[i], &status);//如果设置为可连接,需要使用pthread_join函数来等待线程完成
        if (rc) {
            cout << "unable join" << endl;
            return -1;
        }
        cout << "thread exit:" << index[i] << endl;
    }

    cout << "program exit" << endl;
    pthread_exit(NULL);

    return 0;
}

但是在实际的游戏后台开发中,不会这样直接使用pthread库的,而是先对它进行了封装,然后再使用。例如:

#include <pthread.h>

class Thread
{
    private:
        pthread_t pid;
    private:
        static void * start_thread(void *arg);                                                       //静态成员函数
    public:
        int start();
        virtual void run() = 0;//基类中的虚函数要么实现,要么是纯虚函数(绝对不允许声明不实现,也不纯虚)
};

int Thread::start()
{
        if(pthread_create(&pid,NULL,start_thread,(void *)this) != 0)   //创建一个线程(必须是全局函数),线程一旦被创建就会执行
        {      
            return -1;
        }      
        return 0;
}

void* Thread::start_thread(void *arg) //静态成员函数只能访问静态变量或静态函数,通过传递this指针进行调用
{
    Thread *ptr = (Thread *)arg;
    ptr->run();  
  return 0;                                                                                             //线程的实体是run
}


#include <unistd.h>
#include <stdio.h>
#include "thread.h"
#include <stdlib.h>

class MyThread:public Thread //如果要声明一类线程只需要继承封装好的线程类Thread即可
{
    public:
        void run();
};
void MyThread::run()
{
    printf("hello world\n");
}
       
int main(int argc,char *argv[])
{
    MyThread test;
    test.start();
    printf("------------\n");
    //test.run();
    sleep(1);
    return 0;
}

一个游戏服务中常见的线程有,定时器线程,防止无效访问线程,http服务线程,检查tcp连接线程,等待tcp验证线程,tcp连接主处理线程,tcp连接验证线程,同步验证线程,逻辑主线程,连接回收线程,http连接池线程,http服务主线程等,各个服务器实体下的时间线程等。

参考资料:

https://blog.csdn.net/wuwenjunwwj/article/details/8183502

https://www.cnblogs.com/xianghang123/archive/2011/08/11/2134927.html

https://www.runoob.com/cplusplus/cpp-multithreading.html

https://www.cnblogs.com/yongdaimi/p/12454367.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值