Categories
PHP

PHP Multi Threading :)

Though not available under apache for processing web pages, we do have multi-threading in PHP 🙂

The “pcntl” extension enables multi threading in PHP command line interpreter. That is you can work with php multi threading only from command line. Here’s a code snippet:

The above example first calls the pcntl_fork() function that creates another process with the same data. That is the current execution data is transferred into a new process. Both the processes will advance in the same way. We will have to differentiate the two processes from this point and assign two different tasks to them.

We differentiate the processes by using the return value of the pcntl_fork() function. If the function is successful in creating a new process, it will return two values — one for each of the processes. And a single value if failed. As you can imagine, if it fails, we will have that single process which started at the beginning. On success, we have two processes running at the same time. Both executes the same php script. But the return value of the pcntl_fork() function varies. So, we should add some code to the script that determines the process which is executing the script and act likewise.

The return value of the function could be of three types:
— A Process ID
— 0 (Zero)
— (-1) (Negative One)

If the process that’s executing the script is the child process, it gets the return value 0. And the parent process gets the process ID of the child. (-1) means the forking failed.

On the above example, we have used posix_getpid() and posix_getppid() functions to retrieve the process ID of that process and it’s parent’s.

The process of forking is a bit tough and it took an hour of total wilderness to understand how it really worked. And to be honest, the PHP manual is not that helpful regarding this extension if I compare to other PHP functionalities.

Categories
PHP Python

Creating Dictonaries from Arrays / Lists

PHP:

In PHP, we can create a new associative array or dictionary by using the array_combine() function. Just feed two arrays as the parameters to this function and you get back a dictionary. The first array elements are converted into keys and the second array elements are used as values.

Python:

For Python, we first have to zip() two lists into another lists of tuples containing one element from both lists. Then we use the dict() call on this newly created list to create a dictionary.

I elaborated the process in the above example for beginners. But you’d often see advanced python programmers do it like this:

Categories
Python

Creating Conditional Lists in Python

This post is meant to be short and self explanatory. We can easily create lists in python based on given conditions.

Have a look:

It would create a list containing 1 to 99. I get impressed by the power of Python the more I dig deeper into this fantastic language.