并发计算(Concurrent computing)【代码实现】

C

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
 
pthread_mutex_t condm = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int bang = 0;
 
#define WAITBANG() do { \
   pthread_mutex_lock(&condm); \
   while( bang == 0 ) \
   { \
      pthread_cond_wait(&cond, &condm); \
   } \
   pthread_mutex_unlock(&condm); } while(0);\

void *t_enjoy(void *p)
{
  WAITBANG();
  printf("Enjoy\n");
  pthread_exit(0);
}
 
void *t_rosetta(void *p)
{
  WAITBANG();
  printf("Rosetta\n");
  pthread_exit(0);
}
 
void *t_code(void *p)
{
  WAITBANG();
  printf("Code\n");
  pthread_exit(0);
}
 
typedef void *(*threadfunc)(void *);
int main()
{
   int i;
   pthread_t a[3];
   threadfunc p[3] = {t_enjoy, t_rosetta, t_code};
 
   for(i=0;i<3;i++)
   {
     pthread_create(&a[i], NULL, p[i], NULL);
   }
   sleep(1);
   bang = 1;
   pthread_cond_broadcast(&cond);
   for(i=0;i<3;i++)
   {
     pthread_join(a[i], NULL);
   }
}

C++

#include <thread>
#include <iostream>
#include <vector>
#include <random>
#include <chrono> 
 
int main()
{
  std::random_device rd;
  std::mt19937 eng(rd()); // mt19937 generator with a hardware random seed.
  std::uniform_int_distribution<> dist(1,1000);
  std::vector<std::thread> threads;
 
  for(const auto& str: {"Enjoy\n", "Rosetta\n", "Code\n"}) {
    // between 1 and 1000ms per our distribution
    std::chrono::milliseconds duration(dist(eng)); 
 
    threads.emplace_back([str, duration](){                                                                    
      std::this_thread::sleep_for(duration);
      std::cout << str;
    });
  }
 
  for(auto& t: threads) t.join(); 
 
  return 0;
}

C#

With Threads

static Random tRand = new Random();
 
static void Main(string[] args)
{
	Thread t = new Thread(new ParameterizedThreadStart(WriteText));
	t.Start("Enjoy");
 
	t = new Thread(new ParameterizedThreadStart(WriteText));
	t.Start("Rosetta");
 
	t = new Thread(new ParameterizedThreadStart(WriteText));
	t.Start("Code");
 
	Console.ReadLine();
}
 
private static void WriteText(object p)
{
	Thread.Sleep(tRand.Next(1000, 4000));
	Console.WriteLine(p);
}

With Tasks

using System;
using System.Threading.Tasks;
 
public class Program
{
    static async Task Main() {
        Task t1 = Task.Run(() => Console.WriteLine("Enjoy"));
        Task t2 = Task.Run(() => Console.WriteLine("Rosetta"));
        Task t3 = Task.Run(() => Console.WriteLine("Code"));
 
        await Task.WhenAll(t1, t2, t3);
    }
}

With a parallel loop

using System;
using System.Threading.Tasks;
 
public class Program
{
    static void Main() => Parallel.ForEach(new[] {"Enjoy", "Rosetta", "Code"}, s => Console.WriteLine(s));
}

Go

Channel

package main
 
import (
    "fmt"
    "golang.org/x/exp/rand"
    "time"
)
 
func main() {
    words := []string{"Enjoy", "Rosetta", "Code"}
    seed := uint64(time.Now().UnixNano())
    q := make(chan string)
    for i, w := range words {
        go func(w string, seed uint64) {
            r := rand.New(rand.NewSource(seed))
            time.Sleep(time.Duration(r.Int63n(1e9)))
            q <- w
        }(w, seed+uint64(i))
    }
    for i := 0; i < len(words); i++ {
        fmt.Println(<-q)
    }
}

Afterfunc

package main
 
import (
    "log"
    "math/rand"
    "os"
    "sync"
    "time"
)
 
func main() {
    words := []string{"Enjoy", "Rosetta", "Code"}
    rand.Seed(time.Now().UnixNano())
    l := log.New(os.Stdout, "", 0)
    var q sync.WaitGroup
    q.Add(len(words))
    for _, w := range words {
        w := w
        time.AfterFunc(time.Duration(rand.Int63n(1e9)), func() {
            l.Println(w)
            q.Done()
        })
    }
    q.Wait()
}

Select

package main
 
import "fmt"
 
func main() {
    w1 := make(chan bool, 1)
    w2 := make(chan bool, 1)
    w3 := make(chan bool, 1)
    for i := 0; i < 3; i++ {
        w1 <- true
        w2 <- true
        w3 <- true
        fmt.Println()
        for i := 0; i < 3; i++ {
            select {
            case <-w1:
                fmt.Println("Enjoy")
            case <-w2:
                fmt.Println("Rosetta")
            case <-w3:
                fmt.Println("Code")
            }
        }
    }
}

Java

import java.util.concurrent.CyclicBarrier;
 
public class Threads
{
  public static class DelayedMessagePrinter implements Runnable
  {
    private CyclicBarrier barrier;
    private String msg;
 
    public DelayedMessagePrinter(CyclicBarrier barrier, String msg)
    {
      this.barrier = barrier;
      this.msg = msg;
    }
 
    public void run()
    {
      try
      {  barrier.await();  }
      catch (Exception e)
      {  }
      System.out.println(msg);
    }
  }
 
  public static void main(String[] args)
  {
    CyclicBarrier barrier = new CyclicBarrier(3);
    new Thread(new DelayedMessagePrinter(barrier, "Enjoy")).start();
    new Thread(new DelayedMessagePrinter(barrier, "Rosetta")).start();
    new Thread(new DelayedMessagePrinter(barrier, "Code")).start();
  }
}

Python

import asyncio
 
 
async def print_(string: str) -> None:
    print(string)
 
 
async def main():
    strings = ['Enjoy', 'Rosetta', 'Code']
    coroutines = map(print_, strings)
    await asyncio.gather(*coroutines)
 
 
if __name__ == '__main__':
    asyncio.run(main())
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

辕门骁骑

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值