In multithreading the global variables or resources are shared among threads. I'm using pthread library in c
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void *worker(void *);
int ctr = 0;
pthread_mutex_t lock;
int main(int argc, char *argv[])
{
pthread_t t[2];
int i = 0;
//~ pthread_mutex_init(&lock, NULL);
while(i < 2)
{
pthread_create(&t[i], NULL, &worker, NULL);
i++;
}
pthread_join(t[0], NULL);
pthread_join(t[1], NULL);
//~ pthread_mutex_destroy(&lock);
//~ pthread_join(t[1], NULL);
return 0;
}
void *worker(void *arg)
{
//~ pthread_mutex_lock(&lock);
//~ int ctr = 0;
ctr += 1;
printf("job %d started\n", ctr);
sleep(1);
//~ ctr += 1;
printf("job %d finished\n", ctr);
//~ pthread_mutex_unlock(&lock);
}
This code output :
job 1 started
job 2 started
job 2 finished
job 2 finished
In this code the variable ctr
are shared among thread, and therefore change made by other thread to that variable is visible to another thread (unless a call to some mutexes
is done).
I'm tried that in php but no luck (using php pthreads
).
This is my php code :
global $ctr;
Class WorkerThread extends Worker
{
private $thread_id;
//~ public static $ctr = 0;
private $mutext;
public function WorkerThread($mutex = NULL)
{
//~ $this->ctr = $ctr;
$this->mutex = $mutex;
$this->start();
}
public function run()
{
//~ Mutex::lock($this->mutex);
$new_line = php_sapi_name() == "cli" ? PHP_EOL : "<br>";
//~ global $ctr;
$ctr = 0;
$ctr += 1;
echo "Thread " . $ctr . " started" . " [ " . $this->getThreadId() . " ]" . $new_line;
sleep(1);
echo "Thread " . $ctr . " Finished" . " [ " . $this->getThreadId() . " ]" . $new_line;
//~ var_dump($this);
//~ Mutex::unlock($this->mutex);
}
}
//~ $mutex = Mutex::create();
$i = 0;
$worker = array();
while($i < 2)
{
$worker[$i] = new WorkerThread();
//~ $worker[$i]->start();
$i++;
}
foreach(range(0, 1) as $t)
$worker[$t]->join();
//~ Mutex::destroy($mutex);
Output of this code :
Thread 1 started [ -1257948352 ]
Thread 1 started [ -1267893440 ]
Thread 1 Finished [ -1257948352 ]
Thread 1 Finished [ -1267893440 ]
the variable ctr
(global) not updated by the thread like the c code above?
How to do that in php (sharing resources across threads)?