WeixiangYan/CodeTransOcean huggingface dataset:
Task: Metered concurrency


C++: #include <chrono>
#include <iostream>
#include <format>
#include <semaphore>
#include <thread>
 
using namespace std::literals;

void Worker(std::counting_semaphore<>& semaphore, int id)
{	
    semaphore.acquire();
    std::cout << std::format("Thread {} has a semaphore & is now working.\n", id); 
    std::this_thread::sleep_for(2s);
    std::cout << std::format("Thread {} done.\n", id);
    semaphore.release();
}
 
int main()
{
    const auto numOfThreads = static_cast<int>( std::thread::hardware_concurrency() );
    std::counting_semaphore<> semaphore{numOfThreads / 2};

    std::vector<std::jthread> tasks;
    for (int id = 0; id < numOfThreads; ++id)
	tasks.emplace_back(Worker, std::ref(semaphore), id);

    return 0;
}







VB: Dim sem As New Semaphore(5, 5) 
sem.WaitOne() 
Dim oldCount = sem.Release()
Task: Metered concurrency



C#: using System;
using System.Threading;
using System.Threading.Tasks;

namespace RosettaCode
{
  internal sealed class Program
  {
    private static void Worker(object arg, int id)
    {
      var sem = arg as SemaphoreSlim;
      sem.Wait();
      Console.WriteLine("Thread {0} has a semaphore & is now working.", id);
      Thread.Sleep(2*1000);
      Console.WriteLine("#{0} done.", id);
      sem.Release();
    }

    private static void Main()
    {
      var semaphore = new SemaphoreSlim(Environment.ProcessorCount*2, int.MaxValue);

      Console.WriteLine("You have {0} processors availiabe", Environment.ProcessorCount);
      Console.WriteLine("This program will use {0} semaphores.\n", semaphore.CurrentCount);

      Parallel.For(0, Environment.ProcessorCount*3, y => Worker(semaphore, y));
    }
  }
}


Go: package main

import (
    "log"
    "os"
    "sync"
    "time"
)


type sem chan struct{}

func (s sem) acquire()   { s <- struct{}{} }
func (s sem) release()   { <-s }
func (s sem) count() int { return cap(s) - len(s) }


var fmt = log.New(os.Stdout, "", 0)


const nRooms = 10
const nStudents = 20

func main() {
    rooms := make(sem, nRooms)
    
    
    var studied sync.WaitGroup
    studied.Add(nStudents)
    
    for i := 0; i < nStudents; i++ {
        go student(rooms, &studied)
    }
    studied.Wait()
}

func student(rooms sem, studied *sync.WaitGroup) {
    rooms.acquire()
    
    fmt.Printf("Room entered.  Count is %d.  Studying...\n",
        rooms.count())
    time.Sleep(2 * time.Second) 
    rooms.release()
    studied.Done() 
}
Task: Metered concurrency



C#: using System;
using System.Threading;
using System.Threading.Tasks;

namespace RosettaCode
{
  internal sealed class Program
  {
    private static void Worker(object arg, int id)
    {
      var sem = arg as SemaphoreSlim;
      sem.Wait();
      Console.WriteLine("Thread {0} has a semaphore & is now working.", id);
      Thread.Sleep(2*1000);
      Console.WriteLine("#{0} done.", id);
      sem.Release();
    }

    private static void Main()
    {
      var semaphore = new SemaphoreSlim(Environment.ProcessorCount*2, int.MaxValue);

      Console.WriteLine("You have {0} processors availiabe", Environment.ProcessorCount);
      Console.WriteLine("This program will use {0} semaphores.\n", semaphore.CurrentCount);

      Parallel.For(0, Environment.ProcessorCount*3, y => Worker(semaphore, y));
    }
  }
}



Java: public class CountingSemaphore{
   private int lockCount = 0;
   private int maxCount;

   CountingSemaphore(int Max){
      maxCount = Max;
   }
  
   public synchronized void acquire() throws InterruptedException{
      while( lockCount >= maxCount){
         wait();
      }
      lockCount++;
   }
   public synchronized void release(){
      if (lockCount > 0)
      {
         lockCount--;
         notifyAll();
      }
   }
   public synchronized int getCount(){
      return lockCount;
   }
}

public class Worker extends Thread{
   private CountingSemaphore lock;
   private int id;

   Worker(CountingSemaphore coordinator, int num){
      lock = coordinator;
      id = num;
   }
   Worker(){
   }
   public void run(){
      try{
         lock.acquire();
         System.out.println("Worker " + id + " has acquired the lock.");
         sleep(2000);
      }
      catch (InterruptedException e){
      }
      finally{
         lock.release();
      }
   }
   public static void main(String[] args){
      CountingSemaphore lock = new CountingSemaphore(3);
      Worker crew[];
      crew = new Worker[5];
      for (int i = 0; i < 5; i++){
         crew[i] = new Worker(lock, i);
         crew[i].start();
      }

   }
}
Task: Metered concurrency



C#: using System;
using System.Threading;
using System.Threading.Tasks;

namespace RosettaCode
{
  internal sealed class Program
  {
    private static void Worker(object arg, int id)
    {
      var sem = arg as SemaphoreSlim;
      sem.Wait();
      Console.WriteLine("Thread {0} has a semaphore & is now working.", id);
      Thread.Sleep(2*1000);
      Console.WriteLine("#{0} done.", id);
      sem.Release();
    }

    private static void Main()
    {
      var semaphore = new SemaphoreSlim(Environment.ProcessorCount*2, int.MaxValue);

      Console.WriteLine("You have {0} processors availiabe", Environment.ProcessorCount);
      Console.WriteLine("This program will use {0} semaphores.\n", semaphore.CurrentCount);

      Parallel.For(0, Environment.ProcessorCount*3, y => Worker(semaphore, y));
    }
  }
}





Python: import time
import threading


sem = threading.Semaphore(4)

workers = []
running = 1


def worker():
    me = threading.currentThread()
    while 1:
        sem.acquire()
        try:
            if not running:
                break
            print '%s acquired semaphore' % me.getName()
            time.sleep(2.0)
        finally:
            sem.release()
        time.sleep(0.01) 


for i in range(10):
    t = threading.Thread(name=str(i), target=worker)
    workers.append(t)
    t.start()


try:
    while 1:
        time.sleep(0.1)
except KeyboardInterrupt:
    running = 0
    for t in workers:
        t.join()
Task: Metered concurrency



C#: using System;
using System.Threading;
using System.Threading.Tasks;

namespace RosettaCode
{
  internal sealed class Program
  {
    private static void Worker(object arg, int id)
    {
      var sem = arg as SemaphoreSlim;
      sem.Wait();
      Console.WriteLine("Thread {0} has a semaphore & is now working.", id);
      Thread.Sleep(2*1000);
      Console.WriteLine("#{0} done.", id);
      sem.Release();
    }

    private static void Main()
    {
      var semaphore = new SemaphoreSlim(Environment.ProcessorCount*2, int.MaxValue);

      Console.WriteLine("You have {0} processors availiabe", Environment.ProcessorCount);
      Console.WriteLine("This program will use {0} semaphores.\n", semaphore.CurrentCount);

      Parallel.For(0, Environment.ProcessorCount*3, y => Worker(semaphore, y));
    }
  }
}






VB: Dim sem As New Semaphore(5, 5) 
sem.WaitOne() 
Dim oldCount = sem.Release()
Task: Metered concurrency




Go: package main

import (
    "log"
    "os"
    "sync"
    "time"
)


type sem chan struct{}

func (s sem) acquire()   { s <- struct{}{} }
func (s sem) release()   { <-s }
func (s sem) count() int { return cap(s) - len(s) }


var fmt = log.New(os.Stdout, "", 0)


const nRooms = 10
const nStudents = 20

func main() {
    rooms := make(sem, nRooms)
    
    
    var studied sync.WaitGroup
    studied.Add(nStudents)
    
    for i := 0; i < nStudents; i++ {
        go student(rooms, &studied)
    }
    studied.Wait()
}

func student(rooms sem, studied *sync.WaitGroup) {
    rooms.acquire()
    
    fmt.Printf("Room entered.  Count is %d.  Studying...\n",
        rooms.count())
    time.Sleep(2 * time.Second) 
    rooms.release()
    studied.Done() 
}


Java: public class CountingSemaphore{
   private int lockCount = 0;
   private int maxCount;

   CountingSemaphore(int Max){
      maxCount = Max;
   }
  
   public synchronized void acquire() throws InterruptedException{
      while( lockCount >= maxCount){
         wait();
      }
      lockCount++;
   }
   public synchronized void release(){
      if (lockCount > 0)
      {
         lockCount--;
         notifyAll();
      }
   }
   public synchronized int getCount(){
      return lockCount;
   }
}

public class Worker extends Thread{
   private CountingSemaphore lock;
   private int id;

   Worker(CountingSemaphore coordinator, int num){
      lock = coordinator;
      id = num;
   }
   Worker(){
   }
   public void run(){
      try{
         lock.acquire();
         System.out.println("Worker " + id + " has acquired the lock.");
         sleep(2000);
      }
      catch (InterruptedException e){
      }
      finally{
         lock.release();
      }
   }
   public static void main(String[] args){
      CountingSemaphore lock = new CountingSemaphore(3);
      Worker crew[];
      crew = new Worker[5];
      for (int i = 0; i < 5; i++){
         crew[i] = new Worker(lock, i);
         crew[i].start();
      }

   }
}
Task: Metered concurrency





Java: public class CountingSemaphore{
   private int lockCount = 0;
   private int maxCount;

   CountingSemaphore(int Max){
      maxCount = Max;
   }
  
   public synchronized void acquire() throws InterruptedException{
      while( lockCount >= maxCount){
         wait();
      }
      lockCount++;
   }
   public synchronized void release(){
      if (lockCount > 0)
      {
         lockCount--;
         notifyAll();
      }
   }
   public synchronized int getCount(){
      return lockCount;
   }
}

public class Worker extends Thread{
   private CountingSemaphore lock;
   private int id;

   Worker(CountingSemaphore coordinator, int num){
      lock = coordinator;
      id = num;
   }
   Worker(){
   }
   public void run(){
      try{
         lock.acquire();
         System.out.println("Worker " + id + " has acquired the lock.");
         sleep(2000);
      }
      catch (InterruptedException e){
      }
      finally{
         lock.release();
      }
   }
   public static void main(String[] args){
      CountingSemaphore lock = new CountingSemaphore(3);
      Worker crew[];
      crew = new Worker[5];
      for (int i = 0; i < 5; i++){
         crew[i] = new Worker(lock, i);
         crew[i].start();
      }

   }
}




VB: Dim sem As New Semaphore(5, 5) 
sem.WaitOne() 
Dim oldCount = sem.Release()
Task: Metered concurrency




Go: package main

import (
    "log"
    "os"
    "sync"
    "time"
)


type sem chan struct{}

func (s sem) acquire()   { s <- struct{}{} }
func (s sem) release()   { <-s }
func (s sem) count() int { return cap(s) - len(s) }


var fmt = log.New(os.Stdout, "", 0)


const nRooms = 10
const nStudents = 20

func main() {
    rooms := make(sem, nRooms)
    
    
    var studied sync.WaitGroup
    studied.Add(nStudents)
    
    for i := 0; i < nStudents; i++ {
        go student(rooms, &studied)
    }
    studied.Wait()
}

func student(rooms sem, studied *sync.WaitGroup) {
    rooms.acquire()
    
    fmt.Printf("Room entered.  Count is %d.  Studying...\n",
        rooms.count())
    time.Sleep(2 * time.Second) 
    rooms.release()
    studied.Done() 
}





VB: Dim sem As New Semaphore(5, 5) 
sem.WaitOne() 
Dim oldCount = sem.Release()
Task: Metered concurrency







Python: import time
import threading


sem = threading.Semaphore(4)

workers = []
running = 1


def worker():
    me = threading.currentThread()
    while 1:
        sem.acquire()
        try:
            if not running:
                break
            print '%s acquired semaphore' % me.getName()
            time.sleep(2.0)
        finally:
            sem.release()
        time.sleep(0.01) 


for i in range(10):
    t = threading.Thread(name=str(i), target=worker)
    workers.append(t)
    t.start()


try:
    while 1:
        time.sleep(0.1)
except KeyboardInterrupt:
    running = 0
    for t in workers:
        t.join()


VB: Dim sem As New Semaphore(5, 5) 
sem.WaitOne() 
Dim oldCount = sem.Release()
Task: Metered concurrency

C: #include <semaphore.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

sem_t sem;
int count = 3;


#define getcount() count
void acquire()
{
	sem_wait(&sem);
	count--;
}

void release()
{
	count++;
	sem_post(&sem);
}

void* work(void * id)
{
	int i = 10;
	while (i--) {
		acquire();
		printf("#%d acquired sema at %d\n", *(int*)id, getcount());
		usleep(rand() % 4000000); 
		release();
		usleep(0);  
	}
	return 0;
}

int main()
{
	pthread_t th[4];
	int i, ids[] = {1, 2, 3, 4};

	sem_init(&sem, 0, count);

	for (i = 4; i--;) pthread_create(th + i, 0, work, ids + i);
	for (i = 4; i--;) pthread_join(th[i], 0);
	printf("all workers done\n");

	return sem_destroy(&sem);
}




Go: package main

import (
    "log"
    "os"
    "sync"
    "time"
)


type sem chan struct{}

func (s sem) acquire()   { s <- struct{}{} }
func (s sem) release()   { <-s }
func (s sem) count() int { return cap(s) - len(s) }


var fmt = log.New(os.Stdout, "", 0)


const nRooms = 10
const nStudents = 20

func main() {
    rooms := make(sem, nRooms)
    
    
    var studied sync.WaitGroup
    studied.Add(nStudents)
    
    for i := 0; i < nStudents; i++ {
        go student(rooms, &studied)
    }
    studied.Wait()
}

func student(rooms sem, studied *sync.WaitGroup) {
    rooms.acquire()
    
    fmt.Printf("Room entered.  Count is %d.  Studying...\n",
        rooms.count())
    time.Sleep(2 * time.Second) 
    rooms.release()
    studied.Done() 
}
Task: Metered concurrency





Java: public class CountingSemaphore{
   private int lockCount = 0;
   private int maxCount;

   CountingSemaphore(int Max){
      maxCount = Max;
   }
  
   public synchronized void acquire() throws InterruptedException{
      while( lockCount >= maxCount){
         wait();
      }
      lockCount++;
   }
   public synchronized void release(){
      if (lockCount > 0)
      {
         lockCount--;
         notifyAll();
      }
   }
   public synchronized int getCount(){
      return lockCount;
   }
}

public class Worker extends Thread{
   private CountingSemaphore lock;
   private int id;

   Worker(CountingSemaphore coordinator, int num){
      lock = coordinator;
      id = num;
   }
   Worker(){
   }
   public void run(){
      try{
         lock.acquire();
         System.out.println("Worker " + id + " has acquired the lock.");
         sleep(2000);
      }
      catch (InterruptedException e){
      }
      finally{
         lock.release();
      }
   }
   public static void main(String[] args){
      CountingSemaphore lock = new CountingSemaphore(3);
      Worker crew[];
      crew = new Worker[5];
      for (int i = 0; i < 5; i++){
         crew[i] = new Worker(lock, i);
         crew[i].start();
      }

   }
}



Python: import time
import threading


sem = threading.Semaphore(4)

workers = []
running = 1


def worker():
    me = threading.currentThread()
    while 1:
        sem.acquire()
        try:
            if not running:
                break
            print '%s acquired semaphore' % me.getName()
            time.sleep(2.0)
        finally:
            sem.release()
        time.sleep(0.01) 


for i in range(10):
    t = threading.Thread(name=str(i), target=worker)
    workers.append(t)
    t.start()


try:
    while 1:
        time.sleep(0.1)
except KeyboardInterrupt:
    running = 0
    for t in workers:
        t.join()
Task: Metered concurrency




Go: package main

import (
    "log"
    "os"
    "sync"
    "time"
)


type sem chan struct{}

func (s sem) acquire()   { s <- struct{}{} }
func (s sem) release()   { <-s }
func (s sem) count() int { return cap(s) - len(s) }


var fmt = log.New(os.Stdout, "", 0)


const nRooms = 10
const nStudents = 20

func main() {
    rooms := make(sem, nRooms)
    
    
    var studied sync.WaitGroup
    studied.Add(nStudents)
    
    for i := 0; i < nStudents; i++ {
        go student(rooms, &studied)
    }
    studied.Wait()
}

func student(rooms sem, studied *sync.WaitGroup) {
    rooms.acquire()
    
    fmt.Printf("Room entered.  Count is %d.  Studying...\n",
        rooms.count())
    time.Sleep(2 * time.Second) 
    rooms.release()
    studied.Done() 
}




Python: import time
import threading


sem = threading.Semaphore(4)

workers = []
running = 1


def worker():
    me = threading.currentThread()
    while 1:
        sem.acquire()
        try:
            if not running:
                break
            print '%s acquired semaphore' % me.getName()
            time.sleep(2.0)
        finally:
            sem.release()
        time.sleep(0.01) 


for i in range(10):
    t = threading.Thread(name=str(i), target=worker)
    workers.append(t)
    t.start()


try:
    while 1:
        time.sleep(0.1)
except KeyboardInterrupt:
    running = 0
    for t in workers:
        t.join()
Task: Metered concurrency

C: #include <semaphore.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

sem_t sem;
int count = 3;


#define getcount() count
void acquire()
{
	sem_wait(&sem);
	count--;
}

void release()
{
	count++;
	sem_post(&sem);
}

void* work(void * id)
{
	int i = 10;
	while (i--) {
		acquire();
		printf("#%d acquired sema at %d\n", *(int*)id, getcount());
		usleep(rand() % 4000000); 
		release();
		usleep(0);  
	}
	return 0;
}

int main()
{
	pthread_t th[4];
	int i, ids[] = {1, 2, 3, 4};

	sem_init(&sem, 0, count);

	for (i = 4; i--;) pthread_create(th + i, 0, work, ids + i);
	for (i = 4; i--;) pthread_join(th[i], 0);
	printf("all workers done\n");

	return sem_destroy(&sem);
}





Java: public class CountingSemaphore{
   private int lockCount = 0;
   private int maxCount;

   CountingSemaphore(int Max){
      maxCount = Max;
   }
  
   public synchronized void acquire() throws InterruptedException{
      while( lockCount >= maxCount){
         wait();
      }
      lockCount++;
   }
   public synchronized void release(){
      if (lockCount > 0)
      {
         lockCount--;
         notifyAll();
      }
   }
   public synchronized int getCount(){
      return lockCount;
   }
}

public class Worker extends Thread{
   private CountingSemaphore lock;
   private int id;

   Worker(CountingSemaphore coordinator, int num){
      lock = coordinator;
      id = num;
   }
   Worker(){
   }
   public void run(){
      try{
         lock.acquire();
         System.out.println("Worker " + id + " has acquired the lock.");
         sleep(2000);
      }
      catch (InterruptedException e){
      }
      finally{
         lock.release();
      }
   }
   public static void main(String[] args){
      CountingSemaphore lock = new CountingSemaphore(3);
      Worker crew[];
      crew = new Worker[5];
      for (int i = 0; i < 5; i++){
         crew[i] = new Worker(lock, i);
         crew[i].start();
      }

   }
}
Task: Metered concurrency

C: #include <semaphore.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

sem_t sem;
int count = 3;


#define getcount() count
void acquire()
{
	sem_wait(&sem);
	count--;
}

void release()
{
	count++;
	sem_post(&sem);
}

void* work(void * id)
{
	int i = 10;
	while (i--) {
		acquire();
		printf("#%d acquired sema at %d\n", *(int*)id, getcount());
		usleep(rand() % 4000000); 
		release();
		usleep(0);  
	}
	return 0;
}

int main()
{
	pthread_t th[4];
	int i, ids[] = {1, 2, 3, 4};

	sem_init(&sem, 0, count);

	for (i = 4; i--;) pthread_create(th + i, 0, work, ids + i);
	for (i = 4; i--;) pthread_join(th[i], 0);
	printf("all workers done\n");

	return sem_destroy(&sem);
}








VB: Dim sem As New Semaphore(5, 5) 
sem.WaitOne() 
Dim oldCount = sem.Release()
Task: Call an object method

C: #include<stdlib.h>
#include<stdio.h>

typedef struct{
        int x;
        int (*funcPtr)(int);
}functionPair;

int factorial(int num){
        if(num==0||num==1)
                return 1;
        else
                return num*factorial(num-1);
}

int main(int argc,char** argv)
{
        functionPair response;

        if(argc!=2)
                return printf("Usage : %s <non negative integer>",argv[0]);
        else{
                response = (functionPair){.x = atoi(argv[1]),.funcPtr=&factorial};
                printf("\nFactorial of %d is %d\n",response.x,response.funcPtr(response.x));
        }
        return 0;
}



C#: 
MyClass.Method(someParameter);
 

myInstance.Method(someParameter);
Task: Call an object method

C: #include<stdlib.h>
#include<stdio.h>

typedef struct{
        int x;
        int (*funcPtr)(int);
}functionPair;

int factorial(int num){
        if(num==0||num==1)
                return 1;
        else
                return num*factorial(num-1);
}

int main(int argc,char** argv)
{
        functionPair response;

        if(argc!=2)
                return printf("Usage : %s <non negative integer>",argv[0]);
        else{
                response = (functionPair){.x = atoi(argv[1]),.funcPtr=&factorial};
                printf("\nFactorial of %d is %d\n",response.x,response.funcPtr(response.x));
        }
        return 0;
}


C++: 
MyClass::method(someParameter);


myInstance.method(someParameter);


MyPointer->method(someParameter);
Task: Call an object method

C: #include<stdlib.h>
#include<stdio.h>

typedef struct{
        int x;
        int (*funcPtr)(int);
}functionPair;

int factorial(int num){
        if(num==0||num==1)
                return 1;
        else
                return num*factorial(num-1);
}

int main(int argc,char** argv)
{
        functionPair response;

        if(argc!=2)
                return printf("Usage : %s <non negative integer>",argv[0]);
        else{
                response = (functionPair){.x = atoi(argv[1]),.funcPtr=&factorial};
                printf("\nFactorial of %d is %d\n",response.x,response.funcPtr(response.x));
        }
        return 0;
}




Go: type Foo int 


func (self Foo) ValueMethod(x int) { }


func (self *Foo) PointerMethod(x int) { }


var myValue Foo
var myPointer *Foo = new(Foo)


myValue.ValueMethod(someParameter)

myPointer.PointerMethod(someParameter)



myPointer.ValueMethod(someParameter)



myValue.PointerMethod(someParameter)


Foo.ValueMethod(myValue, someParameter)
(*Foo).PointerMethod(myPointer, someParameter)
(*Foo).ValueMethod(myPointer, someParameter)
Task: Call an object method

C: #include<stdlib.h>
#include<stdio.h>

typedef struct{
        int x;
        int (*funcPtr)(int);
}functionPair;

int factorial(int num){
        if(num==0||num==1)
                return 1;
        else
                return num*factorial(num-1);
}

int main(int argc,char** argv)
{
        functionPair response;

        if(argc!=2)
                return printf("Usage : %s <non negative integer>",argv[0]);
        else{
                response = (functionPair){.x = atoi(argv[1]),.funcPtr=&factorial};
                printf("\nFactorial of %d is %d\n",response.x,response.funcPtr(response.x));
        }
        return 0;
}





Java: 
MyClass.method(someParameter);


myInstance.method(someParameter);
Task: Call an object method

C: #include<stdlib.h>
#include<stdio.h>

typedef struct{
        int x;
        int (*funcPtr)(int);
}functionPair;

int factorial(int num){
        if(num==0||num==1)
                return 1;
        else
                return num*factorial(num-1);
}

int main(int argc,char** argv)
{
        functionPair response;

        if(argc!=2)
                return printf("Usage : %s <non negative integer>",argv[0]);
        else{
                response = (functionPair){.x = atoi(argv[1]),.funcPtr=&factorial};
                printf("\nFactorial of %d is %d\n",response.x,response.funcPtr(response.x));
        }
        return 0;
}







Python: class MyClass(object):
	@classmethod
	def myClassMethod(self, x):
		pass
	@staticmethod
	def myStaticMethod(x):
		pass
	def myMethod(self, x):
		return 42 + x

myInstance = MyClass()


myInstance.myMethod(someParameter)

MyClass.myMethod(myInstance, someParameter)



MyClass.myClassMethod(someParameter)
MyClass.myStaticMethod(someParameter)

myInstance.myClassMethod(someParameter)
myInstance.myStaticMethod(someParameter)