C family Flashcards

(280 cards)

1
Q

Why can C be referred to as being almost a portable assembly language

A

It is as close to the machine as possible while it is almost universally available for existing processor architectures.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What does the statement “C is imperative” mean?

A

It describes computation in terms of statements that change a program state

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What does the statement “C is declarative” mean?

A

describes computation in terms of what it should accomplish

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

C is a procedural/functional language

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What does the statement “C is weakly typed” mean?

A

C supports implicit type conversion

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What does the statement “C is statically typed” mean?

A

Types are checked before runtime so variables must be declared

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are compiler directives and some examples?

A

Special instructions that guide the preprocessor
#include will include the contents of another file - usually containing function prototypes and variable declarations

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the difference between float, double and long double

A

While they are both floating point numbers, double is larger and long double is larger still

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How much memory does a char, short int, int and long int take up?

A

char - 1 byte
short int - 2 bytes
int - 4 bytes
long int - 8 bytes
(unsigned versions take up the same amount of memory)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

To what precision can a float, double and long double hold data and how much memory do they take up?

A

Float, 6 digits, 4 bytes
double, 15 digits, 8 bytes
long double, 18 digits, 16 bytes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

As there is no boolean datatypes in ANSI C, how are conditions evaluated?

A

0 is considered false while any other value is considered true

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How can i create AND and OR conditional statements

A

Double ampersand for AND: &&
Double straight liney thing for OR: ||

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is an advantage and disadvantage of using code short-hands

A

Adv: reduce time to type - may reduce codesize

DisAdv: do not execute any faster and may make code harder to follow

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What do break and continue statements do?

A

Break will break out of the loop and jump to the next command
Continue will jump to the start of next iteration

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the difference between a While and a Do While loop?

A

While loop will check the condition before executing
Do While will execute once before checking the condition is true

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What does “pass by value” mean for functions in C

A

The value of the variable is passed into the function and the value can be used in further calculations. The value of the original variable is not changed

f(variable_name)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What does “pass by reference” mean for functions in C

A

A pointer to the variable is passed to the function, that way processing can be done on the variable and it’s actual value will change

f(*variable_name)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How can we get around C’s functions only being able to return one value if we want to change multilpe

A

Through the use of pointers, if multiple pointers are fed into the function then the values of multiple variables can be changed

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How should we pass arguments into the main function from the command line?

A

It must be defined like this:

int main(int argc, char **argv)

Arg c contains the number of arguments passed and argv is an array of string values. This is not required but is suggested heavily by convention

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What are the values of argv if the program is called myProgram

myProgram Hello 3 “a short sentence”

A

argv[0] = myProgram
argv[1] = Hello
argv[2] = 3
argv[3] = a short sentence

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What are two advantages to using pointers to functions?

A

Functions can be passed as arguments to other functions, oft called callback functions

We can choose which function to execute at runtime based on user inputs

There’s something about qSort on lecture 3 but cba to figure it out

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

How are arrays stored in memory?

A

Arrays are stored contiguously in memory, when an array is initialized an appropriate amount of memory will be reserved

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

How are strings stored in C and what does it mean for a string to be unitialised?

A

A string is stored contiguously as an array of characters, ending in a NULL terminating character ‘\0’.
An string is uninitialized if it hasn’t had characters assinged to it and will contain random stuff until it does

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is a null terminator and what will happen if one does not exist?

A

The null terminator (‘\0’) tells printf when to stop printing out characters

If your string does not have a null terminator, printf carries on plodding through memory and printing out characters until it encounters one.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
What will these print statements output? char name [21] = "Elephants"; printf("*%s*\n", name); printf("*%20s*\n", name); printf("*%-20s*\n", name); printf("*%3s*\n", name); printf("*%-20.3s*\n", name);
They will output: *Elephants* * Elephants* *Elephants * *Elephants* *Ele *
26
Does the strlen function return the length of a string with or without the null terminator?
It will return it without
27
what does strcpy(fullName, firstname) do ?
this will copy the string held in fullName into firstName
28
What will strcat(str1, str2) do?
will concatonate str2 onto the end of str1, overwriting str1
29
How does strcmp(str, str2) work?
This function will return 0 if the two strings are the same, if otherwise it will return another int value
30
What will this statement do? sprintf(fullName, "%s %s", fullName, lastName)
Works very similar to a printf statement but the output of the printf is stored in fullName
31
What is a uniform random number distribution?
A distribution where all values in a defined range are equally likely
32
Why can we not use rand() for statistical modelling?
It does not produce high quality randomness and it not suitable for statistical modelling. It is okay to use if a program just needs a bit of randomness
33
How does seeding work in C and how can srand statements be used?
Seeding refers to the process of initializing a pseudo-random number generator. Without seeding, a rand() will always start from the same internal state, leading to the same sequence of "random" numbers every time you run the program. Seeding is can be a user inputted number but time is often recommended used like: srand(43); srand(time(0)); The second option is the only one that will produce a different number each run
34
What does scanf do?
Will capture a user input which can then be stored
35
What is a stream?
It's an abstraction of a file - this means that a consistent interface can be provided to the programmer stdio.h much be included
36
What does it mean that a stream is buffered?
Data is not necessarily written to the device when the write command is issued, however this can be forced by flushing the stream
37
What are the two types of stream?
Text stream - sequence of characters - character translation may occur binary stream - sequence of bytes - character translation will not occur
38
What are three common functions used to write to a stream - including binary streams
putc() or fputc(ch, fp) - will write a character to a stream fputs(str, fp) - write a string to the stream fwrite() - writes to a binary stream
39
What are three common functions used to read from a stream?
getc() or fgetc(fp) - read a character from a stream and can store it in a variable fgets(str, count, fp) - read a string from a stream up to a max of count characters and stores it in str fread() - read from a binary stream
40
When reading/writing to a stream what is something that must always be tested?
You must always test that opening the file was successful
41
What do these file modes mean? r w a rb wb
read write appending to read a binary file write to a binary file
42
What does fprintf() do?
Works like a printf statement but will ouput the string to the file pointed to by fo fprintf(fp, "String stuff %s", ch)
43
what does fscanf do?
fscanf(fp,"%d,%d",&x,&y); like scanf, but the string is input from the file pointed to by fp
44
What do the following stream functions do? fflush(fp) remove("MyFile.txt") rewind(fp)
fflush(fp) - forces the output buffer to be written to the file remove("myFile.txt") - deletes the specified file -returns 0 on success; other integer on failure rewind(fp) - resets the file position indicator back to the beginning of the file
45
What are three standard streams that all programs can use without calling fopen or fclose?
-stdin input from the keyboard -stdout output to the terminal; normal program output -stderr output to the terminal; error and warning messages
46
Where should error messages be sent and why?
You must ALWAYS send error messages to stderr and not stdout. This is because they will now show as error messages in the terminal
47
How exactly does an #include statement work?
It will find the file after the # and copy it's contents into the current position in the program
48
What is the difference between these statements #include #include "myFile.h"
: search for this file using the path in which the pre-processor expects to find such files "myFile.h": search for this file firstly in the same directory as this program, and then using the path in which the pre-processor expects to find such files
49
Why can using #define be dangerous
Definitions are substituted before the compiler compiles the source code so any errors introduced are hard to trace
50
what do these statements do? #ifdef #ifndef #undef #else #elif #endif
#ifdef if a macro is defined #ifndef if a macro is not defined #undef undefine a macro #else otherwise #elif else if #endif end of the #ifdef or #ifndef block
51
What are some strong macro conventions
Macro names should be all capitals System macros should start with two underscores
52
Why might someone choose to use Macros?
Defining macros can make your code more readable Defining macros are good for values that might change some time in the future
53
What are the four storage classes in C
Auto(default) register static extern
54
What does the register storage class do?
Variable is stored in the CPU's registers for quick access
55
What does the static storage class do?
The variable will continue to exist even after the block in which it is defined terminates Value is retained between repeated calls to the same function Scope is limited to the block in which it is defined function is only visible within its translation unit(it's file)
56
what does the extern storage class do?
The scope is global The function is visible globally
57
How should we name the header (.h file)?
It should always be named after the code (*.c) file it belongs too
58
What are some disadvantages of C being a weakly typed language?
As errors are not checked at compile time there can be type mismatch errors during program execution Unexpected behavior while executing
59
Define a function in C
A uniquely named group of program statements which accepts 0 or more arguments and will return 0 or 1 to the calling code
60
Note: each function in C must have a unique name
61
Define a procedure in C
A procedure is a function which has no return value
62
Why should functions be prototyped?
The (one-pass) compiler needs to know a function's definition before it is called, and functions may appear in any order in the program module. The functions may call each other - so there is no ordering of the function definitions that defines them before they are called The code for the function might not be in this program module.
63
What information is needed to prototype a function and how is it done?
The return type, function name and parameter types are needed (parameter names are not necessary) like: void printArray (char []); or int anIntFunction ();
64
Why are global variables considered very bad practice
They can cause a number of issues in including: -can make code harder to maintain and debug -Reduced encapsulation and modularity -Namespace pollution and conflicts
65
What are static variables?
They are declared using the static keyword and initialized once the function is first called. They will retain their values when they go out of scope
66
What is the lookup table and how does it work?
It's used to find the data assigned to variable names, when a variable is created it's name, type and address are assigned to the lookup table. When the variable is used the name is found in the lookup table and the memory address can be used to find the data in memory
67
Note: pointers are a base datatype
68
How can you assign the memory address of a variable to a pointer
Using the & character, &var is the location where var is stored like this: char ch = 'A'; char *p; p = &ch;
69
How can a memory address be shown in a printf statement?
Using %p
70
How much memory does storing a pointer take?
8 bytes on windows 64, 3 on windows 32
71
In pointer arithmetic how many bytes are added by the statement x++ x is a pointer
2 bytes are added
72
char str[20] = "Hello world!"; char *p = str; What will this printf statement output? printf("p is %s\n", p);
p is Hello World!
73
What is the advantage of using void pointers?
Void pointers can point to any datatype as long as it is cast before use
74
How could i cast a void pointer to a char?
*(char *)p
75
What causes these errors: Memory fault Segmentation fault
Memory fault: trying to access memory it is not allowed access to Segmentation fault: trying to access memory in a way that is not allowed
76
What is an issue that can occur here? char str1[20] = "Goodbye"; char str2[6] = "Hello"; str2[16] = 'x';
The program won't throw any errors however the program could be corrupted as the memory address that would belong to str2[16] will be changed to x. If this is currently being used by another variable it will be corrupted
77
What are some solutions when you don't know how much memory is needed at runtime
The best way is to dynamically allocate memory at runtime using pointers however we can also declare an array whose size is determined at runtime(potential issue is we don't know how much free contiguous memory is available) or process the data in smaller dhunks
78
How could i dynamically allocate memory for an int that is 23 numbers long?
int *p = NULL; p = (int *)malloc(23*sizeof(int)); Note: you must always trap the fact that memory was not allocated
79
What happens when a variable goes out of scope?
Its memory is released
80
What is a memory leak?
When allocated memory is not released even when it goes out of scope/ is not longer needed
81
When using malloc what must also happen?
The memory must be explicity freed like: free(p)
82
What are structures in C?
A type of variable that groups multiple related data items together -The closest thing that C has to a class
83
How can i declare a structure in C?
struct { ; }; This should be done before the function prototypes
84
How can new datatypes be defined using structures and the typedef command?
typedef struct bookStruct BOOK; This can then be used as a datatype in variable declaration like: BOOK myBook; this is identical to struct bookStruct myBook
85
What are some things that will accept a structure as a parameter
A function can accept a structure as a parameter as well as returning one If you create a datatype using a structure then you can have arrays of them e.g. BOOK books[20];
86
How can i access the parameters of a structure with and without a pointer?
Without a pointer: structureName.parameterName With a pointer e.g. BOOK *secondBook; secondBook->parameterName this saves the need for the structure to be de-referenced like: (*secondBook).parameterName
87
What are some situations where a linked list would be used over an array
-When we don't know how many elements the array needs to hold -We don't want to store the elements in a linear structure e.g. a tree -You want to store elements of different datatypes
88
Define a linked list
A data structure containing an ordered sequence of nodes in which each node consists of data and one or more links to other nodes in the sequence.
89
What are some advantages of a linked list
It is a memory-efficient means of storing large data structures It has a speed efficient means of inserting and deleting nodes
90
What is an advantage and two disadvantages of using arrays
With arrays you can go directly to the nth element Disadvantages: -insert delete operations require other elements to be moved -if an element needs to be inserted into a full array then the array must be extended or the program will have to stop
91
How can i define the structure of a list node and initialize an empty list?
struct anode { /*this is where the data variables go e.g. */ char data; struct anode *nextNode }; typedef struct anode NODE; NODE *root = NULL;
92
How can i allocate memory and add a node to a linked list?
Initialise the node: NODE *newNode; Allocate Memory: if ( ( newNode = (NODE *)malloc(sizeof(NODE)) ) == NULL) { ...} Then set the nodes new values: newNode->data = 'A'; newNode->nextNode = NULL; then add it to the empty list: root = newNode;
93
How do i add a new node to the beginning of a linked list
newNode->nextNode = root; root = newNode;
94
How do i add a new node to the end of a linked list
root->nextNode = newNode;
95
How should i add a node in the middle of a linked list
-Find the right place to insert -Link the new node to the tail of the list -Link the head of the list to the new node
96
Should linked list nodes be in contiguous memory?
There is no need for linked nodes to be in contiguous memory
97
What are some advantages of linked lists?
Does not matter where each node is stored in memory insert/delete requires only changing the values of 1/2 pointers Size of linked list is limited only by computer memory Lists may be linked in more than one way
98
What are some disadvantages of linked lists
To find an element you must start from the beginning and follow the pointer
99
What is the wrong way to insert a node to a linked list?
If we first link the head of the list to the new node then we have no idea how to link the tail node to the end of the list and all subsequent items in the list are lost
100
What must we also do for each deleted node
We must also free the memory for each node
101
What is a doubly linked list and why is it useful?
It's where nodes in the list are linked in two distinct orders, for example one order could be alphabetical and one could be chronological
102
What are 4 common types of dynamically linked data structures
-Stacks -queues -circular lists -trees
103
What is POSIX?
It is a family of related standards used for maintaining compatability between variants of UNIX
104
What does POSIX define?
It defines: -application programming interface (API) -command line shells -utility interfaces
105
What set of services does POSIX describe?
It describes: -an interface, written in C -a command interpreter -common utility programs -standard semantics and syntax
106
What is the open group and when was it founded?
Established in 1995 It aims to create a single UNIX specification to ensure compatibility across platforms -918 members in total
107
What are the fully certified varieties of UNIX?
Hewlett Packars: HP-UX IBM: AIX Apple: MacOS X
108
What are the mostly compliant varieties of UNIX?
most Linux distributions Android Cygwin(TF?)
109
What are the three layers UNIX is made up of?
The kernel The shell The program / application layer
110
What is telnet and some properties about it?
A virtual terminal connection -application layer protocol over internet or local area network -interactive text oriented communication -unencrypted
111
What is ssh
It's an encrypted version of telnet
112
What are the standard 3 unix editors and some of their properties
vi - specified in POSIX standard; lightweight ed - line editor; very lightweight emacs - incredibly flexible (and complicated); heavyweight
113
What editor should i use if i want speed and what editor should i use if i want flexibility?
vi for speed emacs for flexibility
114
What will these commands, related to environment variables, do: echo $PATH printenv export ECM2433=~/ecm2433 cd $ECM2433 export PS1="`hostname` $ "
Show the value of the variable called PATH Show the values of all defined variables Set the value of the variable called ECM2433(~/ is the current user's home directory) Set the command line prompt to the name of the current server
115
What is everything in UNIX either?
Everything in UNIX is either a file or a process A file is passive e.g. program code a process is active e.g. running program
116
What does every process have?
-Unique PID(process identifier) -Exactly one parent process (apart from the system swapper which has PID 0) -Zero or more children -A child is spawned when the system fork command is called
117
What do these UNIX process commands do: ps top & jobs bg fg kill nohup nice renice
ps process snapshot top real-time list of processes & run process in the background jobs list of the background child processes of current process bg put a paused job into the background fg bring a background job into the foreground kill kill a process nohup keep a child process running even when the parent process nishes nice lower the priority of a child process as you spawn it renice lower the priority of a current process
118
What do these UNIX redirection commands do? | > <
| pipe > redirect stdout to a new file < redirect stdin from a file
119
What will this UNIX command do? ps -ef | grep -i matlab
Show all processes whose command line includes the text “matlab”, ignoring case -e select all processes -f full-format listing -i ignore case
120
What will this UNIX command do? ps –efH
Show the parent/child hierarchy of all processes -e select all processes -f full-format listing -H show process hierarchy
121
What can be used to show the parent/child hierarchy of all processes?
The top command
122
What is the difference between foreground and background in UNIX
foreground: - your session waits until the process has finished background: - you can continue entering commands while the process runs - the process is killed if the parent process finishes
123
What command can i use to run a program in the background
programName &
124
What are the two ways we can force a process to finish
using the job number like: $jobs -l [1] + 18561 running tempsleep $kill %1 using the PID like: $jobs -l [1] + 18561 running tempsleep $kill 18561
125
How can i enable a child process to continue running when I log out?
$ nohup tempsleep &
126
Which programs should run with higher priority than others?
Background processes should always run at a lower priority than foreground processes e.g. $ nohup nice tempsleep & $ renice -p
127
i have this program called tempsleep.c int main () { sleep(60); return 0; } how can i run it in the foreground and how can i run it in the background?
foreground: $tempsleep background $nice tempsleep
128
How can i fork a process then check to see if the fork was successful?
#include #include int main () { int pid = fork(); //fork the process if ( pid < 0 ) //If the fork fails it returns -1 { fprintf(stderr,"Fork failed.\n"); return 1; } else if ( pid == 0 ) //the child process will always have pid of 0 { /* the child process */ } else { /* the parent process */ } return 0; }
129
What does the fork command do?
It will create a duplicate of the parent process and run it
130
What do these functions do: getpid() getppid()
Will get the PID of the current process Will get the PID of the parent process
131
What will this line do? wpid = (int)waitpid(pid,&status,0);
The parent process will wait for a specific child process belonging to pid to finish
132
What will this line do? wpid = (int)waitpid(0,&status,0);
The parent process will wait for any child process to finish
133
What does execve() do?
It will replace the current process with a new process, by default the process is replaced by a new version of itself however a different process can be specified like: execve("filepath", arguments, environment variables)
134
What are the three ways of communicating between processes and how do they work?
signals: -need to know the PID of the process you are signalling -no data can be transferred -the receiving process does not need to keep checking files: -one process writes a file, the other reads it (need to consider file -locking) -data can be transferred -receiving process has to keep checking pipes: -each process opens one end of a unidirectional “pipe” down which data is sent -the processes must be parent & child, or siblings -data can be transferred -receiving process has to keep checking
135
At what point should a pipe used for process communication be opened and what is the code to open a pipe?
It must be opened before the fork so that the parent and child can share it code: int childpid; int fd[2]; if ( pipe(fd) ) { /* an error occurred */ } childpid = fork(); **Important Note: in this code fd is a file descriptor array that will be populated by the pipe function, fd[0] would hold the file descriptor for reading from the pipe and fd[1] would hold the file descriptor for writing to the pipe.
136
What must be done whenever a process wants to send or receive information along a pipe?
The opposite side of the pipe must be closed to avoid unexpected behavior, like: } /* child process closes up input side of pipe */ close(fd[0]); /* Send "str" through the output side of pipe */ write(fd[1], str, (strlen(str)+1)); }
137
Is fd[0] the input side of a pipe or the output side of a pipe
It's the input side of a pipe, from which the process will receive data
138
What is the code for a process to read and write to a pipe
Read: { char str[] = "Hello Mum!"; /* child process closes up input side of pipe */ close(fd[0]); /* Send "str" through the output side of pipe */ write(fd[1], str, (strlen(str)+1)); } Write: { char buffer[80]; int numBytes; /* parent process closes up output side of pipe */ close(fd[1]); /* Read a string from the input side of the pipe */ numBytes = read(fd[0], buffer, sizeof(buffer)); printf("Parent received string: %s (%d bytes)\n", buffer, numBytes); }
139
What does the kill command do and how does it work?
The kill command enables you to terminate a long-running background process: either by specifying the process number: $ kill %1 or the PID: $ kill 10748 What the kill command is actually doing is sending a signal to the process. The command $ kill 10748 is actually the equivalent of $ kill –TERM 10748 which is sending the SIGTERM signal (please terminate) to the process
140
How can i have my program respond to a specific signal?
note:signal.h must be included #include #include #include void sig_handler (int signo) { if (signo == SIGUSR1) { printf("received SIGUSR1\n"); if ( signal(SIGUSR1,sig_handler) == SIG_ERR ) printf("\ncan't catch SIGUSR1\n"); } } int main () { if ( signal(SIGUSR1,sig_handler) == SIG_ERR ) printf("\ncan't catch SIGUSR1\n"); while(1) sleep(1); return 0;
141
Linux is a multi-tasking operating system, what does that mean? (4 statements)
Each process runs in its own lump of memory - its virtual address space Each virtual address space starts at memory address zero The operating system maps virtual memory addresses to real, physical memory addresses using page tables The virtual address space is usually contiguous in some other operating systems it may be segmented
142
What are some things that are good about virtual memory addressing(6 in total)
Transparency -processes are unaware of virtualisation Protection and isolation -one process cannot interfere with another Flexible memory placement -operating system can move things around in memory Shared memory and memory mapped files -efficient interprocess communication -shared code segments, i.e. dynamic libraries Dynamic memory allocation -grow memory usage on demand Paging -creates the illusion of near-infinite memory
143
What is the virtual address space made up of from the top down and a basic overview
The kernal Stack - auto variables libraries - idt this is important Heap - dynamically allocated memory (via malloc) BSS - uninitialised static variables Data - initialized static variables Text - program machine code and constraints
144
In the virtual memory stack what are the two pointers that must always exist
bp(fp) or base(frame) pointer - this will always point to the top of the current frame of virtual memory sp or stack pointer - this will point to the end of the current frame of virtual memory
145
What exists inside a stack frame?
The return address Address of the previous base (frame) pointer function parameters initialized variables
146
How is fragmentation in the heap caused and how can it be avoided?
It's caused by frequent memory allocation and deallocation, memory on the heap becomes divided into small non-contiguous blocks over time
147
What does the state of an executing program depend on?
Virtual address space: -code: the executing program code -data/BSS: static variables -stack: function return address, parameters, auto variables -heap: dynamically allocated variables Registers, including: -sp: stack pointer -bp: base pointer -pc: program counter
148
What does setjmp do?
It will store the contents of the registers to a buffer, like: #include #include int main () { jmp_buf mainbuf; if ( setjmp(mainbuf) == 0 ) printf("register contents stored\n"); return 0; }
149
What does longjmp do?
It will restore the contents of the registers from a buffer, like: #include #include int main () { jmp_buf mainbuf; int setValue; setValue = setjmp(mainbuf); printf("setValue = %d\n", setValue); if ( setValue != 0 ) return 0; longjmp(mainbuf,2); printf("after longjmp\n"); return 0; }
150
Why might setjmp() and longjmp() be used in a program
They can be used to return the program to an earlier state in its execution, when setjmp() is used the entire program state is saved and when longjmp() is called the state returns to how it was when setjmp() was called. The program will then continue execution back at the setjmp() statement
151
What is a subroutine?
Also known as procedures and functions are used to encapsulate a sequence of instructions for a specific task
152
What is a coroutine
Coroutines are a generalisation of subroutines that allow for suspended execution
153
What is the difference between concurrency and parallelism?
Concurrency: -multiple processes accessing one disk -multiple processes sharing one CPU -time slicing -context switching Parallelism: -Multiple processes running on separate CPU's
154
Give one example usage of coroutines and why they are used
Coroutines are used are in computer games to maintain a high framerate because: -You have a computationally heavy routine that needs to run -You do not want that entire routine to run within one frame -It would impact the frame rate and make the gameplay look jerky -Coroutines can split the computationally heavy single routine whilst yielding “time” back to the game loop, thereby keeping the frame rate stable -The program switches between the coroutine and the game loop So coroutines allow the computationally heavy routine to be split across multiple frames rather than requiring it to finish in one.
155
Note: in the memory jumps lecture it might be worth figuring out the setjmp/longjmp couroutines program, time allowing
156
How do couroutines work with the stack?
Stack pointers will simply move to the function being yielded too and then will move back after
157
With machine code what is the ELF
The ELF (Executable and Linkable Format) header tells Linux how to create a new process (there is a full table on what each of the 31 bytes does but surely this won't come up)
158
What does C++ add onto C?
Classes exception handling function and operator overloading default values for parameters pass by reference
159
What standard of C++ are we using?
C++11
160
How can i write a print statement in C++?
#include #include int main() { std::cout << "Hello world!" << std::endl; return 0; } If we want to avoid having to write the scope resolution operator (std::) we can write a statement like this: #include #include using namespace std; int main() { cout << "Hello world!" << endl; return 0; }
161
In C++ where does cout go and where does cerr go?
cout goes to stdout cerr goes to stderr
162
In C++ what does endl do?
prints a newline and flushes the output buffer
163
What will this line of code output in C++? #include #include using namespace std; int main() { int aNum = 42; cout << setfill('*') << setw(10) << aNum << ";" << aNum << endl; return 0; }
This code will output "********42;42"
164
Note: we can take standard C object code and we can link it into C++
165
How can we perform function overloading in C++
Function overloading in C++ is very easy, to perform it the two different functions must have different numbers or types of parameters, they may also have different return types, like: int myabs (int i) { if ( i<0 ) return -i; else return i; } float myabs (float f) { if ( f<0.0 ) return -f; else return f; }
166
How does class declaration work in C++?
Quite similar to other languages, like this: #define SIZE 100 // Define the Stack class class Stack { int stck[SIZE]; //These are the private class variables int index; public: void push(int); //These will be public member function prototypes int pop(void); };
167
What is a public member function prototype?
A declaration of a function belonging to a class and is accessible from outside the class. Like any other function prototype it specifies the functions name, return type and param list without it's implementation.
168
What are the three access specifiers in C++
private(default) -can only be accessed within the class public -can be accessed by any part of the program protected -Can be accessed by member functions of the class they are declared it -Can also be accessed by member functions of classes derived from the original class, allowing for inheritance
169
How can i use classes in C++
To import the class we must include the class hpp file: #include Then we can use a constructor to create a reference to the class which can then be used to access the class functions, like: int main () { Stack s1; //This is the class constructor function int value; s1.push(23); s1.push(1); value = s1.pop(); return 0; } This could be an example of the Stack.hpp file: #define SIZE 100 // Define the Stack class class Stack { int stck[SIZE]; int index; public: void push(int); int pop(void); };
170
What are constructor and Destructor classes in C++
Constructor classes: -A constructor is a special member function that gets called automatically when an object of the class is created. -It has the same name as the class. -If you don't provide a constructor explicitly, C++ provides a default constructor, which initializes the member variables to default values (e.g., 0 for numeric types, nullptr for pointers). Destructor classes: -A destructor is also a special member function that gets called automatically when an object goes out of scope or is explicitly deleted. -It has the same name as the class preceded by a tilde (~). -Primarily used to release resources used by the object
171
How can we create parameterised constructors in C++
Very similar to in other OOP languages, we can add the parameterized constructors after the class definition like: class NewClass { int a,b; public: NewClass(int,int); // parameterised constructor }; NewClass::NewClass(int i, int j) { a = i; b = j; }
172
How can i add functions to my classes in C++
We have to first prototype it in the class definition and then we can define it after, like: class NewClass { int a,b; public: void showValues(); }; void NewClass::showValues () { cout << "a=" << a; cout << ", b=" << b << endl; }
173
How can we overload parameterised constructors in C++?
We simply have to have a differing number of arguments for each constructor, for example: NewClass::NewClass(int i, int j) { a = i; b = j; } NewClass::NewClass(int i) { a = i; b = 0; }
174
How do default values work with parameterised constructors?
We can add default values to our parameterised constructors which will take effect if the value is not specified when it's called. Keep in mind that only trailing values can be defaulted with the exception of when all values are defaulted. For example we can declare: NewClass::NewClass(int i, int j=0) { a = i; b = j; } Then if we call this like: NewClass nc(3) then the value of a will be 2 and the value of b will be defaulted to 0
175
How can i create an uninitialized int pointer in C++? How can i create it initialized and how can i create a pointer to an array?
To create an uninitialised pointer int *p = new int; To create an initialised pointer: int *p = new int(23); To create a pointer to an array of 25 integers: int *p = new int[25];
176
How can I free pointers in C++?
for a standard pointer delete p; for an array pointer delete[] p;
177
How can i create a pointer to a initialised/unitialised class in C++? How can i create an array of these?
a single MyClass, uninitialised MyClass *c = new MyClass; a single MyClass, initialised with value 43 MyClass *c = new MyClass(43); an array of 25 MyClass’es MyClass *c = new MyClass[25]; note: freeing these pointers is the same as normal
178
What is the difference between creating and freeing pointers belonging to a class in C and C++
C will allocate and free memory like it does with any other pointer When creating a pointerC++ will allocate memory first and then call the constructor When freeing a pointer C++ will call the destructor then deallocate memory
179
How can i do pass by value, pseudo pass by reference and pass by reference in C++
Pass by value: void addTen (int x) { x+=10; } pseudo pass by reference (This requires a pointer to be passed to the function: void addTen (int *x) { *x+=10; } Pass by reference: void addTen (int &x) { x+=10; }
180
What is a reference and how is a variable affected when it's reference is changed?
A reference is an alias for a variable When a reference is changed the vairiable changes to match it
181
What is a copy constructor?
It's a member function that initializes an object using another object of the same class
182
What are static member variables?
They are shared by all objects of the same class They can be accessed even if no objects exist
183
What is multiple inheritence in C++?
It's where a class can inherit properties and behaviors from more than one base class, allowing the combining of functionality of multiple classes
184
What is the general form for class inheritance in C++
General form: class derived-class-name: access specifier base-class-name { //class body} for example: class MySpecialString: public MyString { char type; public: MySpecialString(char, const char *); };
185
What is a friend function in relation to a class?
In relation to a class, a friend function is: a non-member function i.e. a function that is not a member of the class which has access to the private and protected elements of the class i.e. the class for which it is a friend
186
What are two things that friendship(friend functions) is not?
-Inherited: e.g friends' children are not your friends -Transitive: a friend of you friend is not your friend
187
How can i declare a friend function in a class?
Using the key word friend in the class prototyping, like: class MyClass { int a,b; public: MyClass(int, int); friend int sum(MyClass); }; MyClass::MyClass (int i, int j) { a = i; b = j; } int sum (MyClass x) { return x.a + x.b; } This friend function takes a constructed class as an argument
188
How can we create a friend function that's a member of another class?
I dont really understand but like this: class MyOtherClass; // forward reference; a sort of “class prototype” class MyClass { int a,b; public: friend int MyOtherClass::sum(MyClass); void setab(int, int); }; class MyOtherClass { int c; public: int sum(MyClass); }; int MyOtherClass::sum (MyClass x) {...}
189
What is one specific use of friend fucntions?
One specific use of friend functions is in relation to operator overloading
190
What is operator overloading in C++
It's a feature that allows you to redefine the behavior of existing operators for user-defined types (like classes and structs). This means you can make these operators work with your custom data types in a way that mimics how they work with built-in types like integers or strings. for example: the + operator working with complex numbers
191
What is the aim of operator overloading
The aim of operator overloading it to make life easier for users of a class, not for the developer of the class. Easier means: easier to understand the code fewer code defects
192
What operators cannot be overloaded?
. sizeof ?: :: .*
193
How can we implement operator overloading for two custom datatypes?
class MyInteger { int i; public: MyInteger (int i) { this->i = i; } int operator+(MyInteger); }; // This function represents + int MyInteger::operator+ (MyInteger m) { return this->i + m.i; }
194
How can we implement operator overloading for a custom datatype and a non custom datatype
class MyInteger { int i; public: MyInteger (int i) { this->i = i; } int operator+(int); }; // This function represents + int MyInteger::operator+ (int a) { return this->i + a; }
195
Why might we use a friend function in operator overloading?
When we want to add a non custom datatype with a custom datatype, e.g. int+myInt like: class MyInteger { int i; public: MyInteger (int i) { this->i = i; } friend int operator+(int, MyInteger); }; // This function represents + int operator+ (int a, MyInteger m) { return a + m.i; }
196
What are two considerations when using operator overloading
At least one of the operands of an overloaded operator must be of a user-defined type (usually this is a class). Overloaded operators are just function calls, so cannot preserve -associativity e.g. 4 + 3 + 1 = (4 + 3) + 1 = 4 + (3 + 1) -precedence rules e.g. 4 + 3 * 1 = 4 + (3 * 1) ≠ (4 + 3) * 1 of the operator, according to its built-in semantics.
197
What are some plauasible examples for operator overloading?
myString + yourString might concatenate two std::string objects myDate++ might increment a Date object by 1 day a[i] might access the ith element of a MyArray object m(i,j) might access element in row i, column j of a MyMatrix object matrix1 * matrix2 might perform matrix multiplication on two MyMatrix objects
198
What is the difference between [] and () for subscripting?
[] allows only one index e.g. array[4] () allows multiple indices e.g. matrix(5,1)
199
What operator would have to be overloaded to output a date in a custom format?
The << operator found in cout statements
200
How can the << operator be overloaded?
Like this: class MyDate { int year; unsigned int month; unsigned int day; public: MyDate(unsigned int,unsigned int,int); friend ostream &operator<<(ostream &os, MyDate &dt); } ostream &operator<<(ostream &os, MyDate &dt) { os << dt.day << '/' << dt.month << '/' << dt.year; return os; }
201
What is a function template?
It's instructions for how to build a family of similar looking functions
202
How can we implement a function template?
Using the line "template" infront of a function and then replacing any datatypes in the function with T, like: template void myswap (T &x, T &y) { T temp = x; x = y; y = temp; }
203
What is a class template and how can it be implemented?
It's similar to a function template, it allows the building of a family of similar looking classes. It works in the same was as function templates like: template class Stack { T stck[SIZE]; int index; public: static int count; Stack(); Stack(Stack &); ~Stack(); void push(T); T pop(void); };
204
Which data structures are so widely used that C++ provides a set of standard templates?
stacks queues ---
205
What are the four main components in the standard template library(STL)?
Containers -vectors, queues, stack Iterators -objects that enable a program to traverse a container Algorithms -e.g. binary search functions
206
What can exceptions do in C++?
-enable error trapping -allow the transfer of program execution to another part of the code -during execution of the program, i.e. at runtime They can be thrown automatically(e.g. divide by zero) or programmatically
207
How can i throw integer exceptions in C++? How can i throw character exceptions in C++?
throw 20; This will throw exception number 20
208
How can i catch these types of exceptions in C++: Integer exception char exception Catch-all exception
catch (int e) { printf("Integer exception %d\n",e); } catch (char e) { printf("Character exception %e\n",e); } catch (...) { printf("Catch-all exception\n"); } Note: a char catch can only catch char exceptions, same for integer exceptions
209
What happens if an uncaught exception is thrown?
This will output: terminate called after throwing an instance of [...] Abort(coredump)
210
How can we limit the type of exception a function might throw?
In the function declaration we can specify the types like: int myFunction(int i) throw (int,float); If myFunction throws an exception of a different type the program will terminate, abort(coredump)
211
in C++ what do these function declarations mean for the exceptions that can be thrown? int myFunction (int i) throw(); int myFunction (int i);
With the first declaration no exceptions are allowed to be thrown With the second all exceptions are allowed to be thrown
212
What are exception objects in C++
They are instantiated from an exception object class and can be thrown like normal exceptions. They provide a mechanism for handling runtime errors and allow the program to continue execution where a normal exception might have stopped
213
How can i define exception objects in C++?
First we must include exceptions like, #include then we create an exception class that specifies what processing should occur, like: class MyException: public std::exception { virtual const char *what() const throw() { return "My exception happened"; } } Note if we want to use this exception it must be instantiated
214
How can i throw and catch exception objects in C++
To throw one it must first be instantiated from a class, then it can be thrown like any other numerical exception. throw myex; to catch one we need to make use of the exception import, we can do it like: catch ( std::exception &e) { std::cout << e.what() << std::endl; } the line e.what() will output the message that goes with the exception object
215
What causes these standard exceptions from the C++ standard library: bad_alloc bad_cast bad_exception bad_typeid ios_base::failure
thrown by failure to allocate memory thrown by dynamic casts thrown when an exception type does not match any cast thrown by the typeid operator thrown by functions in the iostream library
216
How can we use standard exceptions?
in a standard catch statement like: catch (bad_alloc &b)
217
How can we determine the type of an object or variable at runtime
using typeid() typeid(MyClass).name()
218
What are the 4 standard streams in C++?
cin - standard input (stdin in C) cout - standard output (stdout in C) cerr - standard error output (stderr in C) clog - buffered version on cerr
219
What are these operators >> <<
>> is the extraction operator because it extracts characters from a stream << is the insertion operator because it inserts characters into a stream
220
what are the three stream classes in C++ and what access do they have?
ifstream - read access ofstream - write access fstream - read/write access
221
How do i open a file in C++?
f.open(, ) example: fstream outFile; outFile.open("example.bin", ios::out | ios::app | ios::binary);
222
What do the following file mode flags do in C++? ios::in ios::out ios::binary ios::ate ios::app ios::trunc
read write binary mode set initil position to end of file append if file opened for output and file already exists then overwrite
223
How do i open and close file streams in C++?
#include ifstream inFile; ofstream outFile; inFile.open("myFile.txt"); // ifstream: default mode is ios::in outFile.open("myFile2.txt"); // ofstream: default mode is ios::out if ( !inFile.is_open() || !outFile.is_open() ) // do some error processing inFile.close(); outFile.close();
224
How can i write to a file in C++?
ofstream out("myFile.txt"); // open normal output file if ( !out.is_open() ) { /* error processing */ } out << "Sam " << 1.78 << endl; out << "Chris " << 1.64 << endl; out << "Lindsay " << 1.69 << endl; out.close();
225
How can i read from a file in C++?
ifstream in("myFile.txt"); // open normal input file char name[20]; float height; if ( !in.is_open() ) { /* error processing */ } in >> name >> height; while ( !in.eof() ) { cout << "name: " << name << ", height: " << height <> name >> height; }
226
In C++ file streams what does ignore() do?
Reads and discards characters until either -certain number of characters have been ignored (1 by default) or -the character specified by delim is encountered (EOF by default). used like: ifstream in("test.txt"); if ( in.is_open ) { // ignore up to 10 characters, or until the first space in.ignore(10, ' '); }
227
What do these stream state flags do bad(0 fail() eof() good() clear()
Returns true if a reading or writing operation fails e.g. try to read from a file that is not open for reading, or try to write to a full disk Returns true in the same cases as bad(), but also when a format error happens e.g. try to read an integer value and get an alphabetical character Returns true if a file open for reading has reached the end Returns false where any of the above return true NB: not the opposite of bad() Resets the state flags
228
What is big endian and what is little endian?
big endian: most significant (“biggest”) digit first little endian: least significant (“littlest”) digit first for example: Decimal number: 123 = 100 + 20 + 3 Little endian decimal number would be: 321 = 3 + 20 + 100
229
How can we create a program that can tell whether or not a system is big or little endian?
In C++ we can create a program to exploit how memory addresses are assigned. We create an integer x with the value 1 and cast a character pointer to memory address of x. If the character pointer is 0 then the system will store the most significant byte (in this case 0) first and is big endian If the character pointer is 1 then the system will store the lease significant byte (in this case 1) first and is little endian
230
What do bit fields do?
Bit fiends allow you to address smaller units of memory than one byte
231
How can i create a structure that has bit fields
After the variable name we must add : 1 where 1 is the number of bits the variable will take up, like: struct textflags { unsigned char bold : 1; unsigned char italic : 1; unsigned char underline : 1; }; struct textflags mytext; mytext.bold = 1; mytext.italic = 0; mytext.underline = 1;
232
What are unions in C++ and when might i want to use them
A union is a user-defined data type that allows you to store different data types within the same memory location. However, only one member of the union can hold a value at any given time. Assigning a value to one member effectively overwrites the value in any other member. We might want to use unions when: When you have data that doesn't need to be stored simultaneously, unions can save memory. Since unions can only hold one value that means that we can change two values by writing one variable
233
How is little endian useful for C programs?
It allows easier implicit type conversion, if the system wasn't little endian then pointer arithmetic would have to be performed to convert types (This was wierdly explained in the lecture ngl, i dont get it)
234
What is the bitwise operation for multiplication and division?
left shift by 1 is multiplication by 2, right shift by 1 is division by 2
235
When setting a bit what does this code do? x |= (1 << 5)
it will set the 6th bit of x to 1 00100000
236
What does the const modifier do for the following: variable pointer to const variabile constant pointer to a variable constant pointer to constant variable
variable’s value cannot be changed after initialisation the thing being pointed to cannot be changed cannot change the pointer, but can change the value it is pointing to neither pointer nor thing pointed to can change
237
What are enumerations in C++?
It's a set of user-defined(named) integral constants for example instead of representing days of the week as integers 0 - 6 we can define them as meaningful names, like: enum dayofweek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
238
What is a variadic function?
It's a function that can accept a variable number of parameters, e.g. a printf statement
239
This is an example of a variadic function
#include void myprintf (char *, ...); /* function prototype */ void myprintf (char *p_format, ... ) { va_list ap; char msg[350]; va_start(ap, p_format); vsprintf(msg, p_format, ap); va_end(ap); printf(msg); }
240
What is objective C?
It's essentially C with objects and is a strict superset of C
241
What are the two object oriented frameworks for objective C
Foundation: classes for basic data structures and for interacting with operating system AppKit: classes for developing applications, windows, buttons, etc Foundation + AppKit = Cocoa
242
What are the three stages of an objective C program
Class instantiation Class implementation object instantiation and method calling
243
How can i write hello world in obj C?
#import int main () { NSLog(@"Hello world!\n"); printf("%s\n", [@"Hello world!\n" UTF8String]); return 0; }
244
In Obj C how is #import different to #include
Import does not need any guard statements as it has an added feature that ensures the include code only appears once
245
How can i call a message in obj C
Objective-C messaging: MyObject *obj = [MyObject new]; [obj callWith:parameter1 and:parameter2];
246
In obj C where is memory for objects held and what must all objects be?
Always in the heap and all objects must be pointers
247
How can i declare an object in obj C? How can i declare an object and allocate memory to the pointer in obj C
NSNumber *num1; NSNumber *num2 = [NSNumber alloc];
248
How can i declare an object, allocate memory to the pointer in obj C? How can i declare an object, allocate memory to the pointer and initialise the value from an integer
NSNumber *num3a = [[NSNumber alloc] init]; NSNumber *num4 = [[NSNumber alloc] initWithInteger:43];
249
How can i create new objects in obj C with literal syntax?
BOOL b = YES; NSNumber *num1 = @43; NSNumber *num2 = @'A'; NSNumber *num3 = @91.6; NSNumber *num4 = @b;
250
how can literal syntax be used to initialise strings?
NSString *string = @"Hello World!"; NSLog(@"Hello World!");
251
How can an array of objects be created with and without literal syntax in obj C?
Without literal syntax: NSArray *numbers = [[NSArray alloc] arrayWithObjects : @"one", @"two", @"three", nil]; With literal syntax: NSArray *numbers = @[@"one", @"two", @"three"];
252
Note: in obj C each class will have it's own header file
253
How can we define and implement a new class in obj C
header file: MyClass.h @interface : { } @end implementation file: MyClass.m @implementation @end
254
note: all methods are public in objective C
This is the format: (void)setFirstName:(NSString *)name;
255
How can i declare a method in objective C?
256
A class, person, has a method setFirstName which looks like this (void)setFirstName:(NSString *)name How can i call this method?
Person *me; [me setFirstName:@"Jacq"];
257
How can i call two methods at a time in obj C?
Person *me; [me setFirstName:@"Jacq" andLastName:@"Christmas"];
258
What is the difference between instance and class methods in obj C
Instance methods operate on specific instances of a class and require an object to be created, are declared with a - sign before method name Class methods are associated with the class itself and not a particular object and is called directly with the class name. Declared with a + sign before method name
259
Note: a class method cannot access attributes in obj C
260
How can we use constructors in objective C?
method name always starts with init called after alloc like: NSNumber *anum = [[NSNumber alloc] initWithInteger:@43]; NSNumber *pi = [[NSNumber alloc] initWithFloat:@3.14159];
261
What is an interface(.h file) in objective C
It will define what an object of a class can do An interface is where the properties and methods of the objects are declared( prototypes) begins with @interface and ends with @end
262
What is an implementation(.m file) in objective C?
An implementation contains the actual code that fulfills the prototype functionalities defined in the interface
263
What is a superclass in objective C?
A superclass is a class that serves as a blueprint for other classes. It defines a set of properties and methods that can be inherited by its subclasses. A subclass is a class that inherits properties and methods from a superclass. It can also add its own unique properties and methods, specializing the functionality provided by the superclass. -promotes code reusability -promotes code organisation and polymorphism
264
How can we create a constructor in objective C?
Create an init instance method in the interface, like: @interface Money : NSObject { NSString *currency; float value; } - (id) init; @end Then in the implementation file we need to call the superclass's initializer like self = [super init]; then check it was successful before assigning values to the new object, like: if (self) { currency = @"GBP"; } return self @end
265
What is the id dataype in objective C?
It's a datatype that is a pointer to any type of object, essentially objective C's version of a void pointer. It supports dynamic referencing As a convention used as a return type to a constructor
266
What is dynamic referencing as opposed to static referencing ?
static referencing: object type defined at compile time dynamic referencing: object type defined at runtime
267
What are some properties about destructors in objective C
-Must always be called dealloc -always called automatically by the runtime -never explicitly called
267
What is introspection in objective C?
Introspection refers to the ability of an object to examine itself at runtime and reveal information about its properties, methods, and relationships.
268
How can i implement destructors (dealloc) in objective C?
@interface Person : NSObject @end @implementation Person - (void) dealloc { // do some clean -up operations // then call the parent class's destructor: [super dealloc]; } @end
269
What is manual retain-release in objective C?
Is a technique where the programmer is explicitly responsible for allocating and deallocating memory for objects, it keeps track of how many owners an object has. It's implemented using a model called reference counting which is provided by NSObject and the Objective C runtime
270
How does reference counting work in Objective C
you create a new object -reference count is set to 1 you claim ownership of an object -reference count is incremented by 1 you relinquish ownership of an object -reference count is decremented by 1 object exists while reference count is greater than zero object is destroyed when the reference count becomes zero
271
What do these reference counting methods do and how do they effect the reference count of an object? alloc retain copy release autorelease
Create an object and claim ownership of it and set reference count to 1 Claim ownership of an existing object and increase reference count by one copy an object and claim ownership of it,and set reference count to 1 Relinquish ownership of an object and decrement its reference count by 1 Relinquish ownership of an object but defer it's destruction
272
What is Automatic Reference Counting(ARC)
needs to be switched on in Xcode works the same way as manual reference counting, except ... ... it automatically inserts appropriate retain and release calls means you must not explicitly call retain, release or autorelease means you usually do not need a custom dealloc method
273
What do sockets do?
Enable two nodes on a network to talk to each other
274
What are the 5 server side socket steps
1. create a socket (socket) 2.set socket options (setsockopt) 3.bind the listener process to a specific port number (bind) 4.start listening (listen) 5.whenever a client requests a connection -accept a connection request from a client (accept) -exchange data with the client (send, read) -close connection (close)
275
What are the three client side socket steps
create a socket socket request a connection connect exchange data with the server send, read
276
Threads are lightweight processes, what advantage does this bring?
faster to create faster to switch between faster to communicate between -but only using global or static variables
277
What is mutex and how does it work?
Its a locking mechanism for threads known as mutual exclusion, this means only a single thread can access a shared resource at any time Threads can lock resources while they are using them and unlock resources when they are done
278
What is semaphore and how does it work
Synchronization tool used to control access to shared resources. It acts like a flag that regulates how many threads can access the resource at a time. The semaphore has a count which dictates how many threads can access the resource, when the counter is at 0 then no new threads can access it When a thread access the resource is decrements the count and it increments it when it's finshed
279