首页 > 试题广场 >

多线程

[编程题]多线程
  • 热度指数:45263 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

问题描述:有4个线程和1个公共的字符数组。线程1的功能就是向数组输出A,线程2的功能就是向字符输出B,线程3的功能就是向数组输出C,线程4的功能就是向数组输出D。要求按顺序向数组赋值ABCDABCDABCD,ABCD的个数由线程函数1的参数指定。[注:C语言选手可使用WINDOWS SDK库函数]
接口说明:
void init();  //初始化函数
void Release(); //资源释放函数
unsignedint__stdcall ThreadFun1(PVOID pM)  ; //线程函数1,传入一个int类型的指针[取值范围:1 – 250,测试用例保证],用于初始化输出A次数,资源需要线程释放
unsignedint__stdcall ThreadFun2(PVOID pM)  ;//线程函数2,无参数传入
unsignedint__stdcall ThreadFun3(PVOID pM)  ;//线程函数3,无参数传入
Unsigned int __stdcall ThreadFunc4(PVOID pM);//线程函数4,无参数传入
char  g_write[1032]; //线程1,2,3,4按顺序向该数组赋值。不用考虑数组是否越界,测试用例保证


输入描述:

本题含有多个样例输入。
输入一个int整数



输出描述:

对于每组样例,输出多个ABCD

示例1

输入

10

输出

ABCDABCDABCDABCDABCDABCDABCDABCDABCDABCD
# 思路上是一样的,只是稍微简化了一下,每个线程只需要实例化不同的对象即可
from threading import Thread, Lock

lock = Lock()


class MyThread(Thread):

    def __init__(self, c1, c2, max_n):
        super().__init__()
        self.c1 = c1  # 上一个字符(根据上个字符确定是否需要输入下个字符)
        self.c2 = c2  # 当前字符
        self.max_n = max_n  # 最多需要输入多少个字符
        self.n = 0  # 初始已经输入的字符数量

    def run(self):
        global out
        while self.n < self.max_n:
            lock.acquire()  # 获取锁,不满足条件立即释放
            if out[-1] == self.c1:
                out += self.c2
                self.n += 1
            lock.release()  # 释放锁

while True:
    try:
        max_num = int(input())
        out = 'A'
        thread1 = MyThread('D', 'A', max_num-1)
        thread2 = MyThread('A', 'B', max_num)
        thread3 = MyThread('B', 'C', max_num)
        thread4 = MyThread('C', 'D', max_num)
        tasks = [thread1, thread2, thread3, thread4]
        for task in tasks:
            task.start()
        for task in tasks:
            task.join()
        print(out)
    except:
        break

发表于 2021-06-23 14:22:35 回复(2)
import threading
while True:
    try:
        c = []
        num = int(input())
        def write():
            b = 'ABCD'
            c.append(b)
            return
        for i in range(num):
            t = threading.Thread(target=write)
            t.start()
        print(''.join(c))
    except:
        break
发表于 2021-05-08 15:02:08 回复(2)
我开玩笑
import sys
for line in sys.stdin:
    a = int(line.strip())
    print('ABCD'*a)
发表于 2020-12-22 13:22:04 回复(0)
使用 condition 锁来同步
import sys
from threading import Thread, Condition


sigs, c_lock = "ABCD", Condition()


def task(sig):
    global output, count, g_sig
    while True:
        c_lock.acquire()
        while not sig==g_sig and count:
            c_lock.wait()
        if not count:
            c_lock.notify_all()
            c_lock.release()
            break
        else:
            output += sig
            count, g_sig = count-1, sigs[(12-count+1)%4]
            c_lock.notify_all()
            c_lock.release()
            continue


for n in sys.stdin:
    output, count, g_sig = "", 4*int(n), "A"
    tasks = [Thread(target=task, args=sigs[i]) for i in range(4)]
    for t in tasks:
        t.start()
    for t in tasks:
        t.join()
    print(output)
    


发表于 2020-12-17 15:31:48 回复(0)
# 2020年11月17日18:52:31
while True:
    try:
        n = int(input())
        print("ABCD"*n)
    except:
        break
        

发表于 2020-11-17 18:56:29 回复(2)
"""
思路,四个锁上了的锁, 交给 4个线程去用
当能获取到锁后,释放下一个需要的锁 (但不释放自己的锁,需要等 "前面"一个 来释放)

准备就绪后,用主线程打开第一个锁

"""

from threading import Thread, Lock


def print_char(char, times, in_lock: Lock, out_lock: Lock):
    for _ in range(times):
        in_lock.acquire()
        print(char, end="")
        out_lock.release()


times = int(input())
locks = []
threads = []
for _ in range(4):
    lock = Lock()
    lock.acquire()
    locks.append(lock)

for i, char in enumerate("ABCD"):
    threads.append(Thread(target=print_char, args=(char, times, locks[i], locks[(i + 1) % 4])))

for thread in threads:
    thread.start()

locks[0].release()

for thread in threads:
    thread.join()
print("")

编辑于 2020-10-15 14:56:27 回复(0)
while True:
    try:
        import threading
        global ARR, LOCK, COUNT
        ARR, COUNT, LOCK = [], -1, threading.Lock()

        def a(n):
            global COUNT
            if COUNT == -1:
                COUNT = n * 4
            if COUNT % 4 == 0:
                LOCK.acquire()
                ARR.append("A")
                COUNT -= 1
                LOCK.release()

        def b():
            global COUNT
            if COUNT % 4 == 3:
                LOCK.acquire()
                ARR.append("B")
                COUNT -= 1
                LOCK.release()

        def c():
            global COUNT
            if COUNT % 4 == 2:
                LOCK.acquire()
                ARR.append("C")
                COUNT -= 1
                LOCK.release()

        def d():
            global COUNT
            if COUNT % 4 == 1:
                LOCK.acquire()
                ARR.append("D")
                COUNT -= 1
                LOCK.release()
        times = int(input())
        while COUNT:
            pool = [threading.Thread(target=a, args=(times,)), threading.Thread(target=b),
                    threading.Thread(target=c), threading.Thread(target=d)]
            for t in pool:
                t.start()
                t.join()
        print("".join(ARR))
    except:
        break

这个应该算是符合题意吧
编辑于 2020-08-22 22:23:59 回复(0)
while True:
    try:
        import threading
        # 给每个线程定义锁
        a_lock = threading.Lock()
        b_lock = threading.Lock()
        c_lock = threading.Lock()
        d_lock = threading.Lock()
        count = int(input()) * 4  # 每个字母输出n次,一个4n次输出
        def show_a():
            global count
            while count >= 4:
                a_lock.acquire()
                print("A", end="")
                b_lock.release()
                count -= 1
        def show_b():
            global count
            while count >= 3:
                b_lock.acquire()
                print("B", end="")
                c_lock.release()
                count -= 1
        def show_c():
            global count
            while count >= 2:
                c_lock.acquire()
                print("C", end="")
                d_lock.release()
                count -= 1
        def show_d():
            global count
            while count >= 1:
                d_lock.acquire()
                print("D", end="")
                a_lock.release()
                count -= 1
        thread_list = []
        func_list = [show_a, show_b, show_c, show_d]
        for func in func_list:
            thread = threading.Thread(target=func)
            thread_list.append(thread)
        # 最先输出A,其他线程暂时锁住
        b_lock.acquire()
        c_lock.acquire()
        d_lock.acquire()
        for th in thread_list:
            th.setDaemon(True)
            th.start()  # 开始线程
        for th in thread_list:
            th.join()  # 主线程任务结束之后,进入阻塞状态,一直等待其他的子线程执行结束之后,主线程才终止
        # print("final count", count)
    except:
        break

这段代码在本地IDE测试还有在线自测都没有问题,为什么在提交运行的时候会出现输入22本应该输出长度为88的字符串,却输出了长度为1508的字符串呢?最后打印的count已经变为0,线程也都终止了,为什么还会出现这种情况呢?(备注:本地测试和在线自测输入22可以得到正确结果)

发表于 2020-08-02 14:51:09 回复(1)
# python 版本的多线程实现,参数是传入的
# 很多抖机灵的做法不用线程,其实不妥,不满足题目要求
# 此代码参考了诸多大神的,并最终实现了参数的传入,再次一并向各位大神表示感谢

import threading
 
class MyThread1(threading.Thread):
    
    def __init__(self, args): 
        super(MyThread1, self).__init__()
        self.args = args
    
    def run(self):
        cou=self.args
        global g_write, mutex , cou
        while cou>0:
            if mutex.acquire(1):
                if g_write[-1] == "D":
                    g_write.append("A")
                mutex.release()

class MyThread2(threading.Thread):
    def run(self):
        global g_write, mutex, cou
        while cou>0:
            if mutex.acquire(1):
                if g_write[-1] == "A":
                    g_write.append("B")
                mutex.release()

class MyThread3(threading.Thread):
    def run(self):
        global g_write, mutex, cou
        while cou>0:
            if mutex.acquire(1):
                if g_write[-1] == "B":
                    g_write.append("C")
                mutex.release()

class MyThread4(threading.Thread):
    def run(self):
        global g_write, mutex, cou
        while cou>0:
            if mutex.acquire(1):
                if g_write[-1] == "C":
                    g_write.append("D")
                    cou -= 1
                    if cou <= 0:
                        print(''.join(g_write))
                        mutex.release()
                        break;
                mutex.release()




while True:
    try:
        ins = int(input())
    except:
        break;
    g_write = ["A"]

    mutex = threading.Lock()
    tsk = []
    tsk.append(MyThread1(ins)) 
    tsk.append(MyThread2())
    tsk.append(MyThread3())
    tsk.append(MyThread4())

    for each in tsk:
        each.start()
    for each in tsk:
        each.join()
630ms,5164K,AC
编辑于 2020-06-29 11:35:35 回复(0)
#!usr/bin/env python
while 1:
    try:
        num = int(raw_input())
        print 'ABCD'*num
    except:
        break

发表于 2020-04-12 16:23:26 回复(0)
纯粹为了通过OJ的欺诈方案:
import sys
for line in sys.stdin:
    print("ABCD"*eval(line))


发表于 2020-03-08 17:40:35 回复(0)
# -*- coding: utf-8 -*-
# !/usr/bin/python3
from threading import Thread

s = ''


def method(a):
    global s
    s += a


while True:
    try:
        m = int(input())
        s = ''

        for i in range(m):
            thread_a = Thread(target=method('A'))
            thread_b = Thread(target=method('B'))
            thread_c = Thread(target=method('C'))
            thread_d = Thread(target=method('D'))

            thread_a.start()
            thread_b.start()
            thread_c.start()
            thread_d.start()

        print(s)

    except:
        break
        

发表于 2019-11-27 14:29:27 回复(2)
while True:
    try:
        input_int = int(input())
        re = 'ABCD'*input_int
        print(re)
    except:
        break

发表于 2019-10-19 10:28:00 回复(0)
while True:
    try:
        n=int(input().strip())
        #print(n)
        result=''
        for i in range(n):
            result+='ABCD'
        print(result)
    except:
        break
发表于 2019-06-21 09:08:14 回复(0)
我一直以为我理解错题意了,看见个多线程就把自己吓坏了
发表于 2018-08-01 17:44:34 回复(0)
while True:
    try:
        print("ABCD"*int(input()))
    except:
        break
发表于 2017-09-08 14:02:16 回复(14)

问题信息

难度:
18条回答 59001浏览

热门推荐

通过挑战的用户