Perforce Public Knowledge Base - Using the Derived APIs in Multi-threaded Scripts
Reset Search



Using the Derived APIs in Multi-threaded Scripts

« Go Back



The same P4 instance cannot be used in multiple threads. The workaround is to use separate P4 instances in each thread.

The Perforce client-server protocol is not designed to support multiple concurrent queries over the same connection. For this reason, multi-threaded applications using the C++ API, or the derived APIs for Ruby, Perl, Python, and PHP, must use either a separate connection within each thread, or a single connection using one thread at any given time.

The best method is to put each P4 instance in each new thread, and then free the memory allocated to the P4 instance (or object) by assigning "undef" to the object reference variable. This undef prevents the same object instance from being used in another thread.

See the following P4Perl example for details:
#!/usr/bin/env perl

use warnings;
use strict;
use diagnostics;
use threads;
use threads::shared;
use P4;

print "Starting main program\n";

my @threads;

for(my $count = 1; $count <= 10; $count++) {

  my $newThread = threads->new(\&createThread, $count);


foreach my $newThread (@threads) {

  my $num =$newThread->join;


print "End of main program\n";

sub createThread {

  my $p4 = new P4;
  my $num = shift;

  $p4->Connect( ) or die ("Was not able to connect\n");

  print "Started thread $num\n";
  sleep $num;
  print "Done with thread $num\n";

  $p4->Disconnect( );

  $p4 = undef #deallocate the memory allocated for the object explicitly

  return $num;

Related Links



Was this article helpful?



Please tell us how we can make this article more useful.

Characters Remaining: 255