Python学习——Python 与 C 语法对比8(线程)

承接上篇:

Python学习——Python 与 C 语法对比1(输出、注释、运算符、数字型)-CSDN博客

Python学习——Python 与 C 语法对比2(非数字型)-CSDN博客

Python学习——Python 与 C 语法对比3(条件控制)-CSDN博客

Python学习——Python 与 C 语法对比4(循环)-CSDN博客

Python学习——Python 与 C 语法对比5(函数)-CSDN博客

Python学习——Python 与 C 语法对比6(输入输出)-CSDN博客

Python学习——Python 与 C 语法对比7(类、结构体)-CSDN博客

线程

PythonC语言说明
创建线程import threading
t = threading.Thread(target=function_name)
t.start()
#include <pthread.h>
pthread_t t;
pthread_create(&t, NULL, function_name, NULL);
Python使用threading模块创建线程,而C语言使用POSIX线程库(pthread)创建线程。
线程通信queue = queue.Queue()
queue.put(item)
item = queue.get()
sem_t sem;
sem_init(&sem, 0, 1);
sem_wait(&sem);
sem_post(&sem);
Python使用线程安全的队列进行线程间通信,而C语言可以使用信号量或其他同步原语。
信号处理import signal
signal.signal(signal.SIGINT, handler)
#include <signal.h>
signal(SIGINT, handler);
Python使用signal模块处理信号,而C语言使用signal函数处理信号。
父子进程import os
pid = os.fork()
#include <unistd.h>
pid_t pid = fork();
Python使用os.fork()创建子进程,而C语言使用fork()函数创建子进程。
守护线程t = threading.Thread(target=function_name, daemon=True)
t.start()
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_create(&t, &attr, function_name, NULL);
Python通过设置daemon=True来创建守护线程,而C语言需要使用pthread_attr_t结构体和PTHREAD_CREATE_DETACHED标志来创建守护线程。
普通线程t = threading.Thread(target=function_name)
t.start()
pthread_t t;
pthread_create(&t, NULL, function_name, NULL);
Python默认创建普通线程,而C语言同样默认创建普通线程。
线程结束t.join()pthread_join(t, NULL);Python使用join()方法等待线程结束,而C语言使用pthread_join()函数等待线程结束。

注意:以上表格仅列举了Python和C语言在线程方面的一些主要区别点,实际上两者在其他方面也有不同之处。

举例:创建线程

Python:

import threading

def worker():
    print("Worker thread is running")

t = threading.Thread(target=worker)
t.start()
t.join()

C:

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

void *worker(void *arg) {
    printf("Worker thread is running\n");
    return NULL;
}

int main() {
    pthread_t t;
    pthread_create(&t, NULL, worker, NULL);
    pthread_join(t, NULL);
    return 0;
}

举例:线程通信

Python:

from threading import Thread, Lock

lock = Lock()
shared_data = []

def worker():
    with lock:
        shared_data.append(1)

threads = [Thread(target=worker) for _ in range(10)]
for t in threads:
    t.start()
for t in threads:
    t.join()

print(shared_data)

C:

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

pthread_mutex_t lock;
int shared_data = 0;

void *worker(void *arg) {
    pthread_mutex_lock(&lock);
    shared_data++;
    pthread_mutex_unlock(&lock);
    return NULL;
}

int main() {
    pthread_t threads[10];
    pthread_mutex_init(&lock, NULL);
    for (int i = 0; i < 10; i++) {
        pthread_create(&threads[i], NULL, worker, NULL);
    }
    for (int i = 0; i < 10; i++) {
        pthread_join(threads[i], NULL);
    }
    pthread_mutex_destroy(&lock);
    printf("%d \n", shared_data);
    return 0;
}

举例:信号处理

Python:

import signal
import os
import time

def signal_handler(signum, frame):
    print("Received signal:", signum)

signal.signal(signal.SIGINT, signal_handler)
while True:
    time.sleep(1)

C:

#include <stdio.h>
#include <signal.h>
#include <unistd.h>

void signal_handler(int signum) {
    printf("Received signal: %d\n", signum);
}

int main() {
    signal(SIGINT, signal_handler);
    while (1) {
        sleep(1);
    }
    return 0;
}

举例:父子进程

Python:

import threading
import os

def print_hello():
    print("Hello from thread!")

t = threading.Thread(target=print_hello)
t.start()
t.join()

pid = os.fork()
if pid == 0:
    print("Hello from child process!")
else:
    print("Hello from parent process!")

C:

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

void *print_hello(void *arg) {
    printf("Hello from thread!\n");
    return NULL;
}

int main() {
    pthread_t t;
    pthread_create(&t, NULL, print_hello, NULL);
    pthread_join(t, NULL);

    pid_t pid = fork();
    if (pid == 0) {
        printf("Hello from child process!\n");
    } else {
        printf("Hello from parent process!\n");
    }
    return 0;
}

Python 与 C 在线程和父子进程方面的对比如下:

  1. Python 使用 threading 模块来创建和管理线程,而 C 使用 pthread 库来实现多线程。
  2. Python 的线程是轻量级的,因为它们共享内存空间,而 C 的线程是重量级的,因为它们有自己的栈空间。
  3. Python 的线程同步可以使用 LockRLockSemaphore 等对象,而 C 使用互斥锁(mutex)和其他同步原语来实现线程同步。
  4. Python 的线程间通信可以使用队列(Queue)或其他同步原语,而 C 使用条件变量(condition variables)和信号量(semaphores)来实现线程间通信。
  5. Python 的线程可以继承自 threading.Thread 类并重写 run 方法,而 C 需要定义一个函数指针类型,并在创建线程时传递该函数指针。

举例:创建线程

Python:

import threading
import time

def print_hello():
    print("Hello from daemon thread!")
    time.sleep(5)
    print("Daemon thread finished.")

t = threading.Thread(target=print_hello)
t.daemon = True
t.start()

time.sleep(2)
print("Main thread finished.")

C:

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

void *print_hello(void *arg) {
    printf("Hello from daemon thread!\n");
    sleep(5);
    printf("Daemon thread finished.\n");
    return NULL;
}

int main() {
    pthread_t t;
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
    pthread_create(&t, &attr, print_hello, NULL);
    pthread_attr_destroy(&attr);

    sleep(2);
    printf("Main thread finished.\n");
    return 0;
}

Python 与 C 在线程和守护线程方面的对比如下:

  1. Python 使用 threading 模块来创建和管理线程,而 C 使用 pthread 库来实现多线程。
  2. Python 的线程可以设置为守护线程,当主线程结束时,守护线程会自动退出。而在 C 中,需要手动设置线程属性为守护线程,并在主线程结束时调用相应的函数来等待守护线程结束。

  • 12
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值