Linux c编程之多线程

一、说明

  运行的程序叫进程,进程是系统资源分配的最小单元。而线程是操作系统能够进行运算调度的最小单位。一个进程默认是有一个线程在运行,也叫单线程进程,也可以启动多个线程,叫做多线程进程。
多线程有如下特点:

  • 共用同一进程的地址空间
  • 共享进程的全局变量

二、常用API

2.1 pthread_create()

#include <pthread.h>
int pthread_create(pthread_t *thread,
                   const pthread_attr_t *attr,
                   void *(*start_routine) (void *),
                   void *arg);

作用:创建新线程
参数说明:
  thread: 线程ID,是输出参数,创建成功后,系统将thread设置为线程ID
  attr: 线程属性,使用pthread_attr_init和相关的函数进行初始化。如果该参数为NULL,则使用默认的属性创建线程
  start_routine: 新线程执行的函数
  arg: 新线程的函数参数
返回值:
  成功返回0,失败返回错误号

2.2 pthread_join()

int pthread_join(pthread_t thread, void **retval);

作用:阻塞等待指定的线程终止,回收相应的资源。如果线程已
  经终止,则pthread_join立即返回。
参数说明:
  thread: 线程ID
  retval: 输出参数,用来保存线程的退出状态(比如调
    用pthread_exit()指定的退出值)。如果
    不需要获取退出状态时,可以使用NULL
返回值:
  成功返回0,失败返回错误号

2.3 pthread_cancel()

int pthread_cancel(pthread_t thread);

作用:取消(结束)线程
参数说明:
  thread: 线程ID

2.4 pthread_exit()

void pthread_exit(void *retval);

作用:主动退出线程
参数说明:
  retval: 线程退出状态值。如果线程是非分离状态,则可以在另一个线程通过调用pthread_join获得退出的状态值

2.5 pthread_attr_init()

 int pthread_attr_init(pthread_attr_t *attr);

作用:初始化属性
返回值:成功返回0, 失败返回错误号

2.6 pthread_attr_destroy()

int pthread_attr_destroy(pthread_attr_t *attr);

作用:销毁属性
返回值:成功返回0, 失败返回错误号

2.7 pthread_attr_setdetachstate()

    int pthread_attr_setdetachstate(pthread_attr_t *attr,
            int detachstate);

作用:将线程设置为分离状态
参数说明:
  thread: 线程ID
返回值:成功返回0, 失败返回错误号

2.8 pthread_attr_getdetachstate()

    int pthread_attr_getdetachstate(pthread_attr_t *attr, 
        int *detachstate);

作用:获取分离状态信息
参数说明:
  attr: 属性
  detachstate:分离状态变量,传入参数。
        0:不分离 1:分离
返回值:成功返回0,失败返回错误号

2.9 pthread_t pthread_self()

 pthread_t pthread_self(void);

作用: 获取当前线程的ID
返回值:返回线程的ID

2.10 pthread_detach()

 int pthread_detach(pthread_t thread);

作用: 将线程设置为分离状态
参数说明:
  thread: 线程ID
返回值:成功返回0,失败返回错误号

2.11 pthread_cond_init()

    #include <pthread.h>
    int pthread_cond_init(pthread_cond_t *restrict cond,
              const pthread_condattr_t *restrict attr);

作用:初始化条件变量

2.12 pthread_cond_destroy()

    #include <pthread.h>
    int pthread_cond_destroy(pthread_cond_t *cond);

作用:销毁条件变量

2.13 互斥锁pthread_mutex_xxx()

    #include <pthread.h>
    int pthread_mutex_lock(pthread_mutex_t *mutex);
    int pthread_mutex_trylock(pthread_mutex_t *mutex);
    int pthread_mutex_unlock(pthread_mutex_t *mutex);

注:以上所有的pthread_xxx()函数编译时需要链接thread库(-pthread)

三、实例解析

3.1 最简单的线程

multi_pthread.c:

#include <stdio.h>
#include <string.h>
#include <pthread.h>

void *thread_func(void *arg)
{
    pthread_t tid = 0;

    tid = pthread_self();
    printf("sub tid:%ld in sub thread\n", tid);

    while (1) {
        printf("I am sub pthread\n");
        sleep(1);
    }
}

int main(int argc, char *argv[])
{
    int ret = 0;
    pthread_t tid = 0;
    pthread_t main_tid = 0;
    pthread_attr_t attr;

    ret = pthread_create(&tid, NULL, thread_func, NULL);

    main_tid = pthread_self();
    printf("ret:%d, sub tid:%ld, main tid:%ld\n", ret, tid, main_tid);

    while (1) {
        printf("I am main thread\n");
        sleep(1);
    }

    return 0;
}

Makefile:

all:
	gcc -o a.out multi_pthread.c -lpthread
clean:
	-@rm a.out

注:编译时需要链接pthread库
测试:

$ ./a.out 
ret:0, sub tid:140442318440192, main tid:140442326722368
I am main thread
sub tid:140442318440192 in sub thread
I am sub pthread
I am main thread
I am sub pthread
I am main thread
I am sub pthread
I am main thread
I am sub pthread

3.2 线程参数

3.2.1 变量参数

thread_param.c:

#include <stdio.h>
#include <string.h>
#include <pthread.h>

void *thread_func(void *arg)
{
    pthread_t tid = 0;
    long thread_number = -1;

    thread_number = (long)arg;

    tid = pthread_self();
    printf("tid:%ld, number:%ld\n", tid, thread_number);

    while (1) {
        printf("I am sub pthread, thread number:%ld\n", thread_number);
        sleep(1);
    }
}

int main(int argc, char *argv[])
{
    int ret = 0;
    long i = 0;
    pthread_t tid = 0;
    pthread_t main_tid = 0;

    for (i = 0; i < 3; i++) {
        ret = pthread_create(&tid, NULL, thread_func,  (void *)i);
    }

    while (1) {
        printf("I am main thread\n");
        sleep(1);
    }

    return 0;
}

Makefile:

all:
	gcc -o a.out thread_param.c -lpthread
clean:
	-@rm a.out

测试:

$ ./a.out 
I am main thread
tid:139938984036096, number:2
I am sub pthread, thread number:2
tid:139938992428800, number:1
I am sub pthread, thread number:1
tid:139939000821504, number:0
I am sub pthread, thread number:0
I am main thread
I am sub pthread, thread number:2
I am sub pthread, thread number:1
I am sub pthread, thread number:0

3.2.2 结构体参数

thread.c:

#include <stdio.h>
#include <string.h>
#include <pthread.h>

typedef struct thread_info_s
{
    int number;
    char name[32];
} thread_info_t;

thread_info_t g_thread_info;

void *thread_func(void *arg)
{
    pthread_t tid = 0;
    thread_info_t *thread_info = NULL;

    thread_info = (thread_info_t *)arg;

    tid = pthread_self();
    printf("tid:%ld, name:%s, number:%d\n",
                    tid, thread_info->name, thread_info->number);

    while (1) {
        sleep(1);
    }
}

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

    g_thread_info.number = 1;
    strcpy(g_thread_info.name, "test-thread");

    ret = pthread_create(&tid, NULL, thread_func,  (void *)&g_thread_info);

    while (1) {
        sleep(1);
    }

    return 0;
}

Makefile:

all:
	gcc -o a.out thread.c -lpthread
clean:
	-@rm a.out

测试结果:

$ ./a.out 
tid:140212589033216, name:test-thread, number:1

3.3 线程的退出值及分离属性

3.3.1 退出值为字符串

#include <stdio.h>
#include <string.h>
#include <pthread.h>

void *thread_func(void *arg)
{
    pthread_t tid = 0;

    tid = pthread_self();
    printf("sub tid:%ld\n", tid);

    sleep(3);

    pthread_exit((void *)"hello world");
}

int main(int argc, char *argv[])
{
    int ret = 0;
    pthread_t tid = 0;
    void *exit_value = NULL;

    ret = pthread_create(&tid, NULL, thread_func, NULL);

    pthread_join(tid, (void **)(&exit_value));
    printf("thread exit value:%s\n", (char *)exit_value);

    return 0;
}

测试:

$ ./a.out 
sub tid:140493947586304
thread exit value:hello world

3.3.2 退出值为整型

#include <stdio.h>
#include <string.h>
#include <pthread.h>

void *thread_func(void *arg)
{
    pthread_t tid = 0;
    static int exit_value = 5;

    tid = pthread_self();
    printf("sub tid:%ld\n", tid);

    sleep(3);

    pthread_exit((void *)&exit_value);
}

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

    ret = pthread_create(&tid, NULL, thread_func, NULL);

    pthread_join(tid, (void **)(&exit_value));
    printf("thread exit value:%d\n", *exit_value);

    return 0;
}

测试:

$ ./a.out 
sub tid:139728337950464
thread exit value:5

3.3.3 线程分离状态时

#include <stdio.h>
#include <string.h>
#include <pthread.h>

void *thread_func(void *arg)
{
    pthread_t tid = 0;

    tid = pthread_self();
    printf("sub tid:%ld\n", tid);

    sleep(10);

    pthread_exit((void *)"hello world");
}

int main(int argc, char *argv[])
{
    int ret = 0;
    pthread_t tid = 0;
    void *exit_value = NULL;
    pthread_attr_t thread_attr;
    int detachstate = 1;

    pthread_attr_init(&thread_attr);

    pthread_attr_setdetachstate(&thread_attr, detachstate);

    ret = pthread_create(&tid, &thread_attr, thread_func, NULL);

    pthread_join(tid, (void **)(&exit_value));
    printf("thread exit value:%s\n", (char *)exit_value);

    pthread_attr_destroy(&thread_attr);

    while (1) {
        sleep(2);
    }

    return 0;
}

测试结果:

$ ./a.out 
thread exit value:(null)
sub tid:140123777509120

3.4 同步互斥锁

没加锁之前:
thread.c:

#include <stdio.h>
#include <string.h>
#include <pthread.h>

#define THREAD_NUMBER 3

int g_seq = 0;

void *thread_func(void *arg)
{
    long thread_number = -1;

    thread_number = (long)arg;

    while (1) {
        g_seq++;
        printf("I am sub pthread, thread number:%ld, g_seq:%d\n", thread_number, g_seq);
        usleep(1000);
    }
}

int main(int argc, char *argv[])
{
    int ret = 0;
    long i = 0;
    pthread_t tid[THREAD_NUMBER];

    for (i = 0; i < THREAD_NUMBER; i++) {
        ret = pthread_create(&tid[i], NULL, thread_func,  (void *)i);
    }

    while (1) {
        printf("I am main thread\n");
        sleep(1);
    }

    return 0;
}

Makefile:

all:
	gcc -o a.out thread.c -lpthread
clean:
	-@rm a.out

测试结果:

I am sub pthread, thread number:0, g_seq:1669
I am sub pthread, thread number:2, g_seq:1670
I am sub pthread, thread number:1, g_seq:1671
I am sub pthread, thread number:0, g_seq:1671
I am sub pthread, thread number:2, g_seq:1672
I am sub pthread, thread number:0, g_seq:1673
I am sub pthread, thread number:1, g_seq:1673
I am sub pthread, thread number:2, g_seq:1674
I am sub pthread, thread number:0, g_seq:1675
I am sub pthread, thread number:1, g_seq:1675
I am sub pthread, thread number:2, g_seq:1676
I am sub pthread, thread number:0, g_seq:1677
I am sub pthread, thread number:1, g_seq:1677
I am sub pthread, thread number:2, g_seq:1678
I am sub pthread, thread number:1, g_seq:1679
I am sub pthread, thread number:0, g_seq:1679
I am sub pthread, thread number:2, g_seq:1680

增加锁后:
thread.c:

#include <stdio.h>
#include <string.h>
#include <pthread.h>

#define THREAD_NUMBER 3

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int g_seq = 0;

void *thread_func(void *arg)
{
    long thread_number = -1;

    thread_number = (long)arg;

    while (1) {
        pthread_mutex_lock(&mutex);
        g_seq++;
        printf("I am sub pthread, thread number:%ld, g_seq:%d\n", thread_number, g_seq);
        pthread_mutex_unlock(&mutex);
        usleep(1000);
    }
}

int main(int argc, char *argv[])
{
    int ret = 0;
    long i = 0;
    pthread_t tid[THREAD_NUMBER];

    for (i = 0; i < THREAD_NUMBER; i++) {
        ret = pthread_create(&tid[i], NULL, thread_func,  (void *)i);
    }

    while (1) {
        printf("I am main thread\n");
        sleep(1);
    }

    return 0;
}

Makefile:

all:
	gcc -o a.out thread.c -lpthread
clean:
	-@rm a.out

测试结果:

I am sub pthread, thread number:1, g_seq:814
I am sub pthread, thread number:0, g_seq:815
I am sub pthread, thread number:2, g_seq:816
I am sub pthread, thread number:2, g_seq:817
I am sub pthread, thread number:0, g_seq:818
I am sub pthread, thread number:1, g_seq:819
I am sub pthread, thread number:0, g_seq:820
I am sub pthread, thread number:2, g_seq:821
I am sub pthread, thread number:1, g_seq:822
I am sub pthread, thread number:0, g_seq:823
I am sub pthread, thread number:2, g_seq:824
I am sub pthread, thread number:1, g_seq:825

3.5 同步条件变量

thread.c:

#include <stdio.h>
#include <string.h>
#include <pthread.h>

#define THREAD_NUMBER 3

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int g_flag = 0;

void *producer_func(void *arg)
{
    while (1) {
        pthread_mutex_lock(&mutex);
        printf("%s: get lock, flag is:%d\n", __FUNCTION__, g_flag);
        if (1 == g_flag) {
            printf("%s: flag is 0, wait...\n", __FUNCTION__);
            pthread_cond_wait(&cond, &mutex);
            printf("%s: after wait, flag:%d\n", __FUNCTION__, g_flag);
        }
        printf("%s: sleep 10 seconds\n", __FUNCTION__);  
        sleep(10);
        g_flag = 1;
        printf("%s: sleep finish, flag:%d\n", __FUNCTION__, g_flag);
        printf("%s: send cond signal\n", __FUNCTION__);  
        pthread_cond_signal(&cond);
        printf("%s: release lock\n", __FUNCTION__);  
        pthread_mutex_unlock(&mutex);
    }
}

void *customer_func(void *arg)
{
    while (1) {
        pthread_mutex_lock(&mutex);
        printf("%s: get lock, flag is:%d\n", __FUNCTION__, g_flag);
        if (0 == g_flag) {
            printf("%s: flag is 0, wait...\n", __FUNCTION__);
            pthread_cond_wait(&cond, &mutex);
            printf("%s: after wait, flag:%d\n", __FUNCTION__, g_flag);
        }
        printf("%s: sleep 10 seconds\n", __FUNCTION__);  
        sleep(10);
        g_flag = 0;
        printf("%s: sleep finish, flag:%d\n", __FUNCTION__, g_flag);
        printf("%s: send cond signal\n", __FUNCTION__);  
        pthread_cond_signal(&cond);
        printf("%s: release lock\n", __FUNCTION__);  
        pthread_mutex_unlock(&mutex);
    }
}

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

    ret = pthread_create(&producer_tid, NULL, producer_func, NULL);
    ret = pthread_create(&customer_tid, NULL, customer_func, NULL);

    while (1) {
        sleep(10);
    }

    return 0;
}

Makefile:

all:
	gcc -o a.out thread.c -lpthread
clean:
	-@rm a.out

测试结果:

customer_func: get lock, flag is:0
customer_func: flag is 0, wait...
producer_func: get lock, flag is:0
producer_func: sleep 10 seconds
producer_func: sleep finish, flag:1
producer_func: send cond signal
producer_func: release lock
producer_func: get lock, flag is:1
producer_func: flag is 0, wait...
customer_func: after wait, flag:1
customer_func: sleep 10 seconds
customer_func: sleep finish, flag:0
customer_func: send cond signal
customer_func: release lock
customer_func: get lock, flag is:0
customer_func: flag is 0, wait...
producer_func: after wait, flag:0
producer_func: sleep 10 seconds
  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Linux网络编程中,使用多线程进行收发操作可以提高网络应用程序的并发性能。下面是一个简单的示例代码,说明如何使用多线程进行收发操作。 ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include <sys/socket.h> #include <arpa/inet.h> #define MAX_CLIENTS 10 void *handle_client(void *arg) { int client_fd = *(int *)arg; char buffer[1024]; memset(buffer, 0, sizeof(buffer)); // 接收客户端数据 ssize_t recv_len = recv(client_fd, buffer, sizeof(buffer), 0); if (recv_len > 0) { printf("Received message from client: %s\n", buffer); } // 发送响应给客户端 char response[] = "Hello from server!"; ssize_t send_len = send(client_fd, response, sizeof(response), 0); if (send_len == -1) { perror("send"); } close(client_fd); pthread_exit(NULL); } int main() { int server_fd; struct sockaddr_in server_addr; struct sockaddr_in client_addr; socklen_t client_addr_len = sizeof(client_addr); pthread_t threads[MAX_CLIENTS]; // 创建套接字 server_fd = socket(AF_INET, SOCK_STREAM, 0); if (server_fd == -1) { perror("socket"); exit(1); } // 设置服务器地址 server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = INADDR_ANY; server_addr.sin_port = htons(8080); // 绑定套接字到服务器地址 if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) { perror("bind"); exit(1); } // 监听连接 if (listen(server_fd, MAX_CLIENTS) == -1) { perror("listen"); exit(1); } printf("Server started. Listening on port 8080...\n"); // 接受并处理客户端请求 int i = 0; while (1) { int client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_addr_len); if (client_fd == -1) { perror("accept"); continue; } // 创建线程处理客户端请求 if (pthread_create(&threads[i], NULL, handle_client, &client_fd) != 0) { perror("pthread_create"); continue; } // 分离线程 pthread_detach(threads[i]); i++; if (i >= MAX_CLIENTS) { break; } } close(server_fd); return 0; } ``` 在上面的示例代码中,首先创建了一个服务器套接字,然后绑定到指定的IP地址和端口号。接着,使用`listen`函数监听来自客户端的连接请求。 在主循环中,通过调用`accept`函数接受客户端连接,并且为每个客户端连接创建一个新的线程来处理收发操作。`handle_client`函数是在线程中执行的任务,负责接收客户端数据并发送响应给客户端。 需要注意的是,在多线程编程中,要确保网络资源的正确管理和共享,避免竞争条件和死锁等问题的出现。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浪游东戴河

你就是这个世界的唯一

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值