Global variables aren’t really global in LoadRunner

If you studied programming, you probably know a few little factoids like “global variables are bad”, and “goto is considered harmful”. Some people can even explain why (and in what situations) these statements are true.

One of the reasons global variables are bad is that they will probably cause your code to not be threadsafe.

Many people use global variables in LoadRunner scripts without even wondering if this is going to cause problems when running their vusers as a thread (which is the default behaviour) rather than as a process.

Here is some code to test whether global variables in a LoadRunner script could be a problem:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/*
This script is designed to test whether global variables are really shared between virtual users when 
run in vuser per thread mode.
 
Note that this must be run in the LoadRunner Controller with multiple vusers (obviously).
*/
int vuser_id_global = 0; // global variable. Would expect this to be shared between threads.
 
Action()
{
  int vuser_id_local = 0; // local variable. Would expect this to be visible only to the individual virtual user.
 
  lr_start_transaction("Who am I"); // put a transaction in here, so we can see how many iterations we have done.
 
  // Get vuser id, and overwrite global variable
  lr_whoami(&vuser_id_global, NULL, NULL);
 
  lr_think_time(5); // wait some time, so other vusers will also save their vuser id to the global variable.
 
  // Get vuser id, and store it in a local variable
  lr_whoami(&vuser_id_local, NULL, NULL);
 
  // compare values of global and local variables
  if (vuser_id_global != vuser_id_local) {
    lr_error_message("Global variable has been overwritten");
  }
 
  lr_end_transaction("Who am I", LR_AUTO);
 
  return 0;
}

If you run this code in your LoadRunner controller (with as many virtual users as you like), you will find that you never see the error message. This demonstrates that global variables in LoadRunner are not shared between threads, which will be surprising for anyone with programming skills.

Mercury/HP obviously knows that most people using LoadRunner need to be protected from themselves when writing code (and they don’t want to spend all their time dealing with support queries about scripts that intermittently misbehave).

1 comment

What about if I declare the variable in globals.h ?

What I want to do is to have a variable shared and modifiable by all Vusers, so that some of them stop doing things if others already did it.

I tried with static modifier and pointers, but no results

Any advice will be appreciated, thanks!

Leave a Reply